Maps apple com saddr

Как вызвать iPhone Maps для направлений с текущим местоположением в качестве начального адреса

Я знаю, что можно запустить приложение карт iPhone, вызвав openURL по URL-адресу карт Google с параметрами saddr и daddr со строками местоположения или широтой/долготой (см. Пример ниже).

Но мне интересно, возможно ли, чтобы начальный адрес был в виде «Current Location» закладки карт, чтобы я мог использовать код обработки местоположения приложения Maps. Мой поиск в Google был довольно бесплодным.

За исключением чего-то, чтобы вызвать текущую закладку местоположения вместо myLatLong .

Пред iOS 6

Вам нужно использовать Базовое местоположение, чтобы получить текущее местоположение, но с этой широтой/длинной парой вы можете получить Карты, чтобы направить вас оттуда к адресу или адресу улицы. Вот так:

Наконец, если вы хотите избежать использования CoreLocation для явного поиска текущего местоположения и хотите вместо этого использовать URL-адрес @»http://maps.google.com/maps?saddr=Current+Location&daddr=%@» , то просмотрите эту ссылку, которую я предоставил в комментариях ниже, чтобы узнать, как локализовать Current + Location строка Однако вы используете еще одну недокументированную функцию, и, как отмечает Джейсон МакКрири ниже, она может не работать надежно в будущих выпусках.

Обновление для iOS 6

Изначально Maps использовали карты Google, но теперь Apple и Google имеют отдельные приложения для карт.

1) Если вы хотите выполнить маршрутизацию с помощью приложения Google Maps, используйте схему URL-адреса comgooglemaps :

2) Чтобы использовать Apple Maps, вы можете использовать новый класс MKMapItem для iOS 6. См. Документы Apple API здесь

По сути, вы будете использовать что-то вроде этого, если направляетесь к месту назначения координаты ( latlong ):

Чтобы поддерживать iOS 6+ и pre iOS 6 в одном и том же коде, я бы порекомендовал использовать что-то вроде этого кода, который Apple имеет на странице документации API MKMapItem :

Это предполагает, что ваш Xcode Base SDK является iOS 6 (или Latest iOS).

Это работает, но только когда язык iPhone/iPod установлен на английском языке. Если вы хотите поддерживать другие языки, вам нужно будет использовать локализованную строку, соответствующую имени закладки Карты.

Это работает на iPhone:

Вы можете использовать препроцессор #define, например:

чтобы понять вашу версию iOS. Затем я также могу использовать этот код для поддержки iOS 6:

Из-за песочницы у вас нет доступа к закладкам приложения «Карта».

Вместо этого используйте Core Location, чтобы определить текущее местоположение самостоятельно. Затем используйте это местоположение (последний и длинный) в URL-адресе, который вы создаете, чтобы открыть Карты.

Я рекомендую проверить CMMapLauncher , мини-библиотеку, которую я создал для запуска Apple, Google и других приложений для сопоставления iOS с определенным запросом сопоставления. С CMMapLauncher код для получения направления в вашем вопросе будет:

Как вы можете видеть, он также инкапсулирует проверку версии, требуемую между iOS 6 и другими.

Привет, так как iOS6 вышел!

Apple сделала что-то замечательное в плохом смысле (с моей точки зрения).

Карты Apple запускаются, и для устройств под управлением iOS 6 не следует использовать maps.google.com/?q= , если вы хотите, чтобы iDevice открывал собственное приложение Plan. Теперь это будет maps.Apple.com/?q= .

Чтобы разработчикам не пришлось много работать, дружественный сервер maps.Apple.com перенаправляет все устройства, не принадлежащие Apple, на maps.google.com, поэтому изменения будут прозрачными.

Таким образом, мы, разработчики, просто должны переключить все строки запросов Google на Apple ……. Это то, что мне очень не нравится.

Я должен был реализовать эту функциональность сегодня, поэтому я сделал это. Но я чувствовал, что мне не следует просто переписывать каждый URL, лежащий на мобильном веб-сайте, на целевой сервер карт Apple, поэтому я решил просто обнаружить серверную часть iDevices и обслуживать URL-адреса Apple только для них. Я думал, что поделюсь.

Я использую PHP, поэтому я использовал библиотеку Mobile Detect с открытым исходным кодом: http://code.google.com/p/php-mobile-detect/

Просто используйте псевдо-метод isiPad в качестве логического метода получения, и все готово, вы не будете конвертировать Google в Apple 😉

Это просто требует немного кодирования.

Если вы не хотите запрашивать разрешения на местоположение и у вас нет лат и lng, используйте следующее.

Читайте также:  Распознавание звуков айфон как работает

Для ios5 текущее местоположение должно быть на правильном языке. Я использую LocalizedCurrentLocation из этого поста http://www.martip.net/blog/localized-current-location-string-for-iphone-apps

Для ios6 я использую CLGeocoder для получения метки, а затем открываю карту с ней и текущим местоположением.

Не забудьте добавить CoreLocation.framework и MapKit.framework

Для iOS 6 в документации Apple рекомендуется использовать эквивалентные карты. URL-схема Apple.com

так что пользуйтесь

чтобы быть обратно совместимым, код будет

для URL-схемы Apple Maps существует множество других поддерживаемых параметров: Справочник по схеме URL-адресов Apple

вы можете использовать эти макросы определения версии iOS, если у вас есть условный код в других частях вашего кода. Макросы версии iOS

Вы можете сделать это сейчас в формате html только с URL-адреса только на вашем мобильном устройстве. Вот пример . Круто то, что если вы превратите это в qr-код, у вас есть возможность, чтобы кто-то узнал, куда вы направляетесь, где бы он ни находился, просто отсканировав его на своем телефоне.

Мое предложение будет использовать OpenInGoogleMaps-iOS , поскольку это актуальный выбор (к ноябрю 2015 года), он поддерживает установку какао-бобов, и вы готовы сделать это несколькими щелчками мыши.

Установить с помощью: pod «OpenInGoogleMaps»

Требовать в заголовочном файле, используя: #import «OpenInGoogleMapsController.h»

Пример кода ниже:

В текущей версии Google Maps просто пропустите параметр sadr :

saddr :… Если значение оставить пустым, будет использоваться текущее местоположение пользователя.

Для приложения iOS6 Maps вы можете просто использовать тот же URL-адрес, указанный выше http://maps.google.com/maps?saddr=%f,%f&daddr=%@

но вместо URL-адреса карт Google вы используете URL с maps:// , в результате чего получается следующий URL: maps://saddr=%f,%f&daddr=%@.

Использование «текущего местоположения», похоже, не работает, поэтому я остался с координатами.

Еще одна хорошая вещь: он обратно совместим: на iOS5 он запускает приложение Google Maps.

Я ответил на это в другой теме. ( Текущее местоположение не работает с Apple Maps IOS 6 ). Сначала нужно получить координаты текущего местоположения, а затем использовать его для создания URL-адреса карты.

Если вы не предоставите местоположение источника, оно будет принимать текущее местоположение в качестве источника. Попробуйте ниже код

Источник

Apple URL Scheme Reference

The maps URL scheme is used to show geographical locations and to generate driving directions between two points. If your app includes address or location information, you can use map links to open that information in the Maps app in iOS or macOS.

Unlike some schemes, map URLs do not start with a “maps” scheme identifier. Instead, map links are specified as regular http links and are opened either in Safari or the Maps app on the target platform.

Table 5-1 lists the supported parameters along with a brief description of each.

Table 5-1 Supported Apple Maps parameters

The map type. If you don’t specify one of the documented values, the current map type is used.

m (standard view)

k (satellite view)

The query. This parameter is treated as if its value had been typed into the Maps search field by the user. Note that q=* is not supported

The q parameter can also be used as a label if the location is explicitly defined in the ll or address parameters.

A URL-encoded string that describes the search object, such as “pizza,” or an address to be geocoded

The address. Using the address parameter simply displays the specified location, it does not perform a search for the location.

An address string that geolocation can understand.

A hint used during search. If the sll parameter is missing or its value is incomplete, the value of near is used instead.

A comma-separated pair of floating point values that represent latitude and longitude (in that order).

The location around which the map should be centered.

The ll parameter can also represent a pin location when you use the q parameter to specify a name.

A comma-separated pair of floating point values that represent latitude and longitude (in that order).

The zoom level. You can use the z parameter only when you also use the ll parameter; in particular, you can’t use z in combination with the spn or sspn parameters.

A floating point value between 2 and 21 that defines the area around the center point that should be displayed.

The area around the center point, or span. The center point is specified by the ll parameter.

You can’t use the spn parameter in combination with the z parameter.

A coordinate span (see MKCoordinateSpan ) denoting a latitudinal delta and a longitudinal delta.

The source address to be used as the starting point for directions.

A complete directions request includes the saddr , daddr , and dirflg parameters, but only the daddr parameter is required. If you don’t specify a value for saddr , the starting point is “here.”

An address string that geolocation can understand.

The destination address to be used as the destination point for directions.

A complete directions request includes the saddr , daddr , and dirflg parameters, but only the daddr parameter is required.

An address string that geolocation can understand.

The transport type.

A complete directions request includes the saddr , daddr , and dirflg parameters, but only the daddr parameter is required. If you don’t specify one of the documented transport type values, the dirflg parameter is ignored; if you don’t specify any value, Maps uses the user’s preferred transport type or the previous setting.

r (by public transit)

The search location. You can specify the sll parameter by itself or in combination with the q parameter. For example, http://maps.apple.com/?sll=50.894967,4.341626&z=10&t=s is a valid query.

A comma-separated pair of floating point values that represent latitude and longitude (in that order).

The screen span. Use the sspn parameter to specify a span around the search location specified by the sll parameter.

A coordinate span (see MKCoordinateSpan ) denoting a latitudinal delta and a longitudinal delta.

You can use the maps URL scheme to help the user:

Perform a search

Get directions to a location

View a specific location

To perform a search, supply a properly encoded URL string as the value of the q parameter. For example:

To specify a location for search, you can supply a value for the near parameter, or combine the sll parameter with either the z or sspn parameters. You can also set the map type using the t parameter, as shown here:

To provide navigation directions from one location to another, supply the start and destination addresses in the saddr and daddr parameters as shown below. You can also supply much more detail for the start and destination addresses than is shown here.

To specify a transport type, you can use the dirflg parameter as shown here:

You can omit the start address when you want to provide directions “from here.” The following example shows a search from here that provides driving directions in a hybrid map.

To display a specific location, use the ll parameter to center the map at the specified position as shown here:

Another way to display a location is to specify an address, such as:

If you use both the ll and address parameters, ll takes precedence over address . If you include a name in the value of the q parameter, Maps tries to match the name at the specified location.

Copyright © 2017 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2017-09-19

Источник

Как открыть Apple Maps направление движения, пройдя адрес

Я пытаюсь реализовать функцию, которая открывает экран направления движения приложения Apple Map, передавая фактический адрес.

Адрес — это не просто случайные адреса, но и служебные адреса, которые в основном зарегистрированы и доступны для поиска на картах Apple. Таким образом, передавая адрес, он должен быть сопоставлен и правильно указывать направление к этому бизнесу, а не указывать на неизвестную аннотацию на карте. Такой случай происходит, когда я напрямую передаю долготу и широту, поэтому я не хочу использовать geocodeAddressString () для преобразования адреса в геокоординацию.

Как мне этого добиться?

2 ответа

Просто используйте Apple Maps API. Если вы можете найти компанию, указав ее название в Apple Maps, вы можете найти ее через API. В вашем случае правильный параметр — daddr , например:

Вы можете комбинировать несколько параметров, например ваше начальное местоположение:

Вы можете найти список поддерживаемых параметров здесь.

Не забудьте открыть URL через UIApplication.shared().open(url: URL, options: [String: AnyObject], completionHandler: ((Bool) -> Void)?) — в iOS 10 — или UIApplication.shared.open(url: URL)

Вы можете вызывать карты с URL-адресом (как описано Никола), но для этого также есть подходящий API: MKMapItem

    в основном вы создаете элементы карты для POI / адресов [1 или более]

открыть Карты с ними [используйте launchOptions, чтобы начать с маршрутов]

Источник

How to invoke iPhone Maps for Directions with Current Location as Start Address

I know it’s possible to start the iPhone maps application by calling openURL on a google maps URL with parameters saddr and daddr with location strings or Lat/Long (see example below).

But I’m wondering if it’s possible to make the start address be the «Current Location» maps bookmark so that I can use the Maps app’s location handling code. My Google search has been pretty fruitless.

Except with something to invoke the current location bookmark in place of myLatLong .

16 Answers 16

Pre iOS 6

You need to use Core Location to get the current location, but with that lat/long pair, you can get Maps to route you from there, to a street address or location. Like so:

Finally, if you do want to avoid using CoreLocation to explicitly find the current location, and want to use the @»http://maps.google.com/maps?saddr=Current+Location&daddr=%@» url instead, then see this link that I provided in comments below for how to localize the Current+Location string. However, you are taking advantage of another undocumented feature, and as Jason McCreary points out below, it may not work reliably in future releases.

Update for iOS 6

Originally, Maps used Google maps, but now, Apple and Google have separate maps apps.

1) If you wish to route using the Google Maps app, use the comgooglemaps URL scheme:

2) To use Apple Maps, you can use the new MKMapItem class for iOS 6. See the Apple API docs here

Basically, you will use something like this, if routing to destination coordinates ( latlong ):

In order to support both iOS 6+ and pre iOS 6 in the same code, I’d recommend using something like this code that Apple has on the MKMapItem API doc page:

This would assume that your Xcode Base SDK is iOS 6 (or Latest iOS).

This works but only when the iPhone/iPod language is set in English. If you want to support other languages you’ll have to use a localized string to match the Maps bookmark name.

This works on iPhone:

You can use a preprocessor #define like:

to understand your iOS version. Then, I can use this code to support iOS 6, too:

Because of sandboxing, you don’t have access to the Map application’s bookmarks.

Instead, use Core Location to determine the current location yourself. Then use that location (the lat and long) in the URL you build to open Maps.

I recommend checking out CMMapLauncher, a mini-library that I built to launch Apple, Google, and other iOS mapping apps with a specific mapping request. With CMMapLauncher, the code to get the directions in your question would be:

As you can see, it also encapsulates the version checking required between iOS 6 & others.

Hey since iOS6 is out!

Apple did something remarkable in a bad way (from my point of view).

Apple’s maps are launched and for devices running iOS 6 you should not use maps.google.com/?q= if you want the iDevice to open the native Plan app. Now it would be maps.apple.com/?q= .

So that developers don’t have to much work, the friendly maps.apple.com server redirects all non-Apple devices to maps.google.com so the change is transparent.

This way we developpers just have to switch all google query strings to apple ones. This is what I dislike a lot.

I had to implement that functionnality today so I did it. But I felt I should not just rewrite every url lying in mobile website to target Apple’s maps server so I thought I’d just detect iDevices server-side and serve apple urls just for those. I thought I’d share.

I’m using PHP so I used the opensource Mobile Detect library : http://code.google.com/p/php-mobile-detect/

Just use the isiPad pseudo method as a boolean getter and you’re done, you wont convert google into apple 😉

Источник

Читайте также:  Есть проблемы с американским iphone
Оцените статью