Как я открыть Google Maps для направлений, используя координаты на Iphone

голоса
18

Я использую UIMapView для отображения местоположения на iPhone. Я хочу, чтобы сделать маршрут от текущего местоположения до места интереса, я не думаю, что его можно с помощью MapKit (но если это, пожалуйста, сообщите) Так что я буду открывать либо приложение Google Maps или сафари, чтобы отобразить его.

Могу ли я сделать это, указав координаты из (текущего местоположения) в координаты (место расположения интереса) у меня есть эта широта и долгота. Или я должен использовать адреса улиц?

Если я должен использовать адреса улиц, я могу получить их от широты и долготы.

Задан 10/10/2009 в 14:58
источник пользователем
На других языках...                            


7 ответов

голоса
75

Да, это не возможно с помощью MapKit. Вы могли бы попытаться сформировать запрос на URL-адрес Google Maps, который содержит как ваше текущее местоположение и пункт назначения, который будет открываться в приложении Google Maps с направлениями.

Вот пример URL:

http://maps.google.com/?saddr=34.052222,-118.243611&daddr=37.322778,-122.031944

Вот как можно реализовать это в коде:

CLLocationCoordinate2D start = { 34.052222, -118.243611 };
CLLocationCoordinate2D destination = { 37.322778, -122.031944 };    

NSString *googleMapsURLString = [NSString stringWithFormat:@"http://maps.google.com/?saddr=%1.6f,%1.6f&daddr=%1.6f,%1.6f",
                                 start.latitude, start.longitude, destination.latitude, destination.longitude];

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:googleMapsURLString]];
Ответил 12/10/2009 в 06:37
источник пользователем

голоса
4

Используйте сильфон код для обоих Google и яблочных карт в Swift 3 -

if UIApplication.shared.canOpenURL(URL(string: "comgooglemaps://")!)
        {
            let urlString = "http://maps.google.com/?daddr=\(destinationLocation.latitude),\(destinationLocation.longitude)&directionsmode=driving"

            // use bellow line for specific source location

            //let urlString = "http://maps.google.com/?saddr=\(sourceLocation.latitude),\(sourceLocation.longitude)&daddr=\(destinationLocation.latitude),\(destinationLocation.longitude)&directionsmode=driving"

            UIApplication.shared.openURL(URL(string: urlString)!)
        }
        else
        {
            //let urlString = "http://maps.apple.com/maps?saddr=\(sourceLocation.latitude),\(sourceLocation.longitude)&daddr=\(destinationLocation.latitude),\(destinationLocation.longitude)&dirflg=d"
            let urlString = "http://maps.apple.com/maps?daddr=\(destinationLocation.latitude),\(destinationLocation.longitude)&dirflg=d"

            UIApplication.shared.openURL(URL(string: urlString)!)
        }
Ответил 04/01/2017 в 19:42
источник пользователем

голоса
2

Это possible.Use MKMapView Получить координируют место , где вы нажали по телефону и с помощью двух координат запросить KML файл с веб - службы Google, разобрать KML файл (образец приложение KML зрителя в сайте разработчика) и отображать маршруты .. ..
Спасибо

Ответил 29/06/2011 в 07:23
источник пользователем

голоса
1

Первая карта проверки Google установлена ​​в устройстве или нет

if ([[UIApplication sharedApplication] canOpenURL:
         [NSURL URLWithString:@"comgooglemaps://"]]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"comgooglemaps://?saddr=23.0321,72.5252&daddr=22.9783,72.6002&zoom=14&views=traffic"]];
    } else {
        NSLog(@"Can't use comgooglemaps://");
    }

Добавить схему запроса в .plist

<key>LSApplicationQueriesSchemes</key>
<array>
 <string>comgooglemaps</string>
</array>
Ответил 15/06/2017 в 11:06
источник пользователем

голоса
1

Можно маршрут MapKit показать: Просто используйте MKPolyline

Я получаю строку из полилинии googleMapsApi. Я разобрать его на сервер с PHP и возвращает строку окончательное polilyne мое приложение.

NSMutableArray *points = [myApp decodePolyline:[route objectForKey:@"polyline"]];

if([points count] == 0)
{
    return;
}

// while we create the route points, we will also be calculating the bounding box of our route
// so we can easily zoom in on it. 
MKMapPoint northEastPoint; 
MKMapPoint southWestPoint; 

// create a c array of points. 
MKMapPoint* pointArr = malloc(sizeof(CLLocationCoordinate2D) * [points count]);

for(int idx = 0; idx < points.count; idx++)
{
    // break the string down even further to latitude and longitude fields. 
    NSString* currentPointString = [points objectAtIndex:idx];
    NSArray* latLonArr = [currentPointString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];

    CLLocationDegrees latitude  = [[latLonArr objectAtIndex:0] doubleValue];
    CLLocationDegrees longitude = [[latLonArr objectAtIndex:1] doubleValue];

    // create our coordinate and add it to the correct spot in the array 
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);

    MKMapPoint point = MKMapPointForCoordinate(coordinate);

    if (idx == 0) {
        northEastPoint = point;
        southWestPoint = point;
    }
    else 
    {
        if (point.x > northEastPoint.x) 
            northEastPoint.x = point.x;
        if(point.y > northEastPoint.y)
            northEastPoint.y = point.y;
        if (point.x < southWestPoint.x) 
            southWestPoint.x = point.x;
        if (point.y < southWestPoint.y) 
            southWestPoint.y = point.y;
    }
    pointArr[idx] = point;
    _currentLenght++;
}

// create the polyline based on the array of points. 
self.routeLine = [MKPolyline polylineWithPoints:pointArr count:points.count];

_routeRect = MKMapRectMake(southWestPoint.x, southWestPoint.y, 
                           northEastPoint.x - southWestPoint.x, 
                           northEastPoint.y - southWestPoint.y);

// clear the memory allocated earlier for the points
free(pointArr);

if (nil != self.routeLine) {
        [self.mapView addOverlay:self.routeLine];
}
[self.mapView setVisibleMapRect:_routeRect];

И показывает:

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
MKOverlayView* overlayView = nil;

if(overlay == self.routeLine)
{
    self.routeLineView = [[[MKPolylineView alloc] initWithPolyline:self.routeLine] autorelease];
    self.routeLineView.fillColor = [UIColor blueColor];
    self.routeLineView.strokeColor = TICNavigatorColor;
    self.routeLineView.lineWidth = 7;
    self.routeLineView.lineJoin = kCGLineJoinRound;
    self.routeLineView.lineCap = kCGLineCapRound;

    overlayView = self.routeLineView;
}

return overlayView; 
}

Дайте ему попробовать.

Ответил 28/09/2012 в 07:53
источник пользователем

голоса
1

Твердое решение создать контроллер с СИБ, который включает в себя UIWebView вида, а затем передать URL, который осуществляет услуги карты / направление Google. Таким образом, вы держать пользователя в приложении. Такой подход не является достаточным, когда подтягивание веб-страницы, так как комплект Apple, не поддерживает масштабирование. Но с OS4, по крайней мере, пользователь может дважды щелкнуть кнопку домой и переключиться обратно в приложение.

Ответил 07/05/2010 в 00:55
источник пользователем

голоса
-1

Вы можете по электронной почте булавки к себе и, когда вы открываете ссылку по электронной почте, он будет показывать координаты.

Ответил 18/08/2011 в 06:54
источник пользователем

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more