106

I rather thought this would not be so hard to find out but appearantly it is not easy to find an awesome cross device article, like you'd expect.

I want to create a link which opens either the mobile device's browser and surf to google maps OR open a maps app (Apple Maps or Google Maps) and directly starting a route, i.e.: start at the current location, end at a given point (lat/long).

I can test on two devices (beside browserstack), an Android and an iPhone.

The following link works only on the Android:

<a href="http://maps.google.com/maps?daddr=lat,long&amp;ll=">Take me there!</a>

Clicking this link in iPhone's Chrome, this weirdly opens Google Maps in desktop version with ads on the mobile app...

This one only works on iOS, opening Apple Maps asking me to enter a start location (i can pick "Current Location") and start the route = desired behavior. Clicking this link completely fails on Android:

<a href="maps://maps.google.com/maps?daddr=lat,long&amp;ll=">Take me there!</a>

Notice the maps:// protocol.

Is there an elegant cross device way of creating such a link? One link that works on all main mobiles?

Thanks

UPDATE: Solution found (kinda)

Here is what I've come up with. It's not quite what I imagined, though it's working.

var ua = navigator.userAgent.toLowerCase(),
    plat = navigator.platform,
    protocol = '',
    a,
    href;

$.browser.device = ua.match(/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera/i) ? ua.match(/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera/i)[0] : false;


if ($.browser.device) {
    switch($.browser.device) {
        case 'iphone':
        case 'ipad':
        case 'ipod':
            function iOSversion() {
              if (/iP(hone|od|ad)/.test(navigator.platform)) {
                // supports iOS 2.0 and later: <http://bit. ly/TJjs1V>
                var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
                return [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
              }
            }

            var ver = iOSversion() || [0];

            if (ver[0] >= 6) {
              protocol = 'maps://';
            }
            else {
                protocol = 'http://maps.google.com/maps';
            }
        break;

        case 'android':
        default:
            protocol = 'http://maps.google.com/maps';
        break;
    }

a.attr('href', protocol + href)

the maps:// protocol is the url scheme for the apple maps app, which will only start working on ios 6 or higher. There are ways to test if gmaps is installed and then chose what to do with the url, but that was kind of too much for what I intended. So i just ended up creating a maps:// OR maps.google.com/ link, using the above parameters.

** UPDATE **

sadly, $.browser.device don't work since jquery 1.9 (source - http://api.jquery.com/jquery.browser )

Kalnode
  • 9,386
  • 3
  • 34
  • 62
Alex
  • 9,911
  • 5
  • 33
  • 52
  • 1
    What server side language do you use? You could solve this problem with user-agent sniffing. – Uooo Sep 12 '13 at 11:31
  • I know that I could, but I want to make that cross browser. I have PHP and JS – Alex Sep 12 '13 at 13:43
  • @Alex - How would you translate this to work on desktops? So that `maps.google.com` works on Android and Desktop, and `maps:// ` on iOS. – kaoscify Feb 22 '15 at 21:57
  • @Alex - I keep getting an error saying `a` (the last line) is undefined. I have a URL inside an infoWindow that I need it to change depending on the device used. – kaoscify Feb 22 '15 at 22:35
  • post a fiddle of your code – Alex Feb 23 '15 at 08:28
  • 1
    I found that none of the answers really did a great job at detecting the platform (not the browser) so I found [PgwBrowser](http://pgwjs.com/pgwbrowser/), a jQuery plugin that detects platform (eg. desktop, mobile), browser, and even OS. Its also > 2 KB, when compressed and gzipped. With it, I can simply check the os.group in a `switch` statement and route the browser accordingly. – filoxo Apr 22 '15 at 17:57

11 Answers11

110

I haven't worked much with phones, so I dont't know if this would work. But just from a html/javascript point of view, you could just open a different url depending on what the user's device is?

<a style="cursor: pointer;" onclick="myNavFunc()">Take me there!</a>

function myNavFunc(){
    // If it's an iPhone..
    if( (navigator.platform.indexOf("iPhone") != -1) 
        || (navigator.platform.indexOf("iPod") != -1)
        || (navigator.platform.indexOf("iPad") != -1))
         window.open("maps://www.google.com/maps/dir/?api=1&travelmode=driving&layer=traffic&destination=[YOUR_LAT],[YOUR_LNG]");
    else
         window.open("https://www.google.com/maps/dir/?api=1&travelmode=driving&layer=traffic&destination=[YOUR_LAT],[YOUR_LNG]");
}
peterh
  • 11,875
  • 18
  • 85
  • 108
James
  • 4,146
  • 1
  • 20
  • 35
  • Your and Alex Pretzlav answers are the closest that worked for me, but yours goes more into the direction of how it could look when using javascript, thank you. i will update my post to provide the final solution – Alex Sep 20 '13 at 12:16
  • 2
    I researched this a lot about a year ago and can tell you that using using http://maps.apple.com/?q=Mexican+Restaurant will redirect to the google page (try it!) and in the exception where it is a device which has the apple maps app, it will open that app instead. For everything else it will open the google maps app/page. bounty pls. – Worthy7 Nov 10 '16 at 00:18
  • 1
    Specifically what you are looking for is this: http://maps.apple.com/?daddr=San+Francisco&dirflg=d&t=h And the documentation is here: https://developer.apple.com/library/content/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html – Worthy7 Nov 10 '16 at 00:23
  • @Worthy7 apparently, I haven't tested, but on an android the maps.apple.com/* will redirect to the google maps website, whereas maps.google.com/* will allow you to select a native maps app. – James Nov 10 '16 at 09:32
  • 1
    I would highly recommend using [this answer](https://stackoverflow.com/a/10204962/4973023) to open the user map application on Android instead of a new browser page ! – PaulCo May 30 '18 at 14:09
  • What does '&ll=' do? – rmutalik Jun 19 '19 at 00:05
33

Interestingly, http://maps.apple.com links will open directly in Apple Maps on an iOS device, or redirect to Google Maps otherwise (which is then intercepted on an Android device), so you can craft a careful URL that will do the right thing in both cases using an "Apple Maps" URL like:

http://maps.apple.com/?daddr=1600+Amphitheatre+Pkwy,+Mountain+View+CA

Alternatively, you can use a Google Maps url directly (without the /maps URL component) to open directly in Google Maps on an Android device, or open in Google Maps' Mobile Web on an iOS device:

http://maps.google.com/?daddr=1+Infinite+Loop,+Cupertino+CA

Alex Pretzlav
  • 15,505
  • 9
  • 57
  • 55
  • 1
    So I took my Android phone, opened Google Chrome web browser and entered the URL `http://maps.google.com/`. It just opened this URL in that URL in the web browser. I expected it to open the [Google Maps app](https://play.google.com/store/apps/details?id=com.google.android.apps.maps). Did I misunderstood what you wrote here, Alex Pretzlav? ;-) – Leo Sep 09 '14 at 14:17
  • 3
    @Leo Android handles URLs differently when entered directly in the browser vs clicking on a link. Try emailing yourself a google maps URL like http://maps.google.com/?daddr=1600+Amphitheatre+Pkwy,+Mountain+View+CA and then tapping on it from your email client. – Alex Pretzlav Sep 22 '14 at 15:49
  • Thanks @AlexPretzlav. Yes, they have some job to do there to get things together. Are there any emerging standards? – Leo Sep 22 '14 at 19:42
  • 1
    Posting this as a URL so I can test on my android http://maps.apple.com/?daddr=1600+Amphitheatre+Pkwy,+Mountain+View+CA The above URL redirects to google maps (the website) on my android, whereas the `maps.google.com` allows me to open a number of different directions apps on my android phone. – raphael Jun 14 '16 at 20:37
15

just bumped in this question and found here all the answers I took some of the codes above and made simple js function that works on android and iphone (it supports almost every android and iphones).

  function navigate(lat, lng) {
    // If it's an iPhone..
    if ((navigator.platform.indexOf("iPhone") !== -1) || (navigator.platform.indexOf("iPod") !== -1)) {
      function iOSversion() {
        if (/iP(hone|od|ad)/.test(navigator.platform)) {
          // supports iOS 2.0 and later
          var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
          return [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
        }
      }
      var ver = iOSversion() || [0];

      var protocol = 'http://';
      if (ver[0] >= 6) {
        protocol = 'maps://';
      }
      window.location = protocol + 'maps.apple.com/maps?daddr=' + lat + ',' + lng + '&amp;ll=';
    }
    else {
      window.open('http://maps.google.com?daddr=' + lat + ',' + lng + '&amp;ll=');
    }
  }

The html:

 <a onclick="navigate(31.046051,34.85161199999993)" >Israel</a>
talsibony
  • 8,448
  • 6
  • 47
  • 46
13

This works for me on all devices [ iOS, Android and Window Mobile 8.1 ].

Does not look like the best way by any means... but cannot be more simpler :)

<a href="bingmaps:?cp=18.551464~73.951399">
 <a href="http://maps.apple.com/maps?q=18.551464, 73.951399"> 
   Open Maps
 </a>
</a>

http://jsbin.com/dibeq

deepakssn
  • 5,195
  • 2
  • 24
  • 19
6
if (navigator.geolocation) { //Checks if browser supports geolocation
navigator.geolocation.getCurrentPosition(function (position) {                                                                                            
 var latitude = position.coords.latitude;                    //users current
 var longitude = position.coords.longitude;                 //location
 var coords = new google.maps.LatLng(latitude, longitude); //Creates variable for map coordinates
 var directionsService = new google.maps.DirectionsService();
 var directionsDisplay = new google.maps.DirectionsRenderer();
 var mapOptions = //Sets map options
 {
   zoom: 15,  //Sets zoom level (0-21)
   center: coords, //zoom in on users location
   mapTypeControl: true, //allows you to select map type eg. map or satellite
   navigationControlOptions:
   {
     style: google.maps.NavigationControlStyle.SMALL //sets map controls size eg. zoom
   },
   mapTypeId: google.maps.MapTypeId.ROADMAP //sets type of map Options:ROADMAP, SATELLITE, HYBRID, TERRIAN
 };
 map = new google.maps.Map( /*creates Map variable*/ document.getElementById("map"),    mapOptions /*Creates a new map using the passed optional parameters in the mapOptions parameter.*/);
 directionsDisplay.setMap(map);
 directionsDisplay.setPanel(document.getElementById('panel'));
 var request = {
   origin: coords,
   destination: 'BT42 1FL',
   travelMode: google.maps.DirectionsTravelMode.DRIVING
 };

 directionsService.route(request, function (response, status) {
   if (status == google.maps.DirectionsStatus.OK) {
     directionsDisplay.setDirections(response);
   }
 });
 });
 }
Sudharsun
  • 741
  • 6
  • 23
  • 1
    thats a really cool way of doing it, but not quite what i asked for. id rather just want to add an anchor-tag, nothing more. if its not possible without creating a google map with a route itself, that be nice to know. thank you anyways, you get an upvote! – Alex Sep 20 '13 at 10:55
  • Ok let me know if you get a solution – Sudharsun Sep 20 '13 at 12:05
5

Well no, from an iOS developer prospective, there are two links that I know of that will open the Maps app on the iPhone

On iOS 5 and lower: http://maps.apple.com?q=xxxx

On iOS 6 and up: http://maps.google.com?q=xxxx

And that's only on Safari. Chrome will direct you to Google Maps webpage.

Other than that you'll need to use a URL scheme that basically beats the purpose because no android will know that protocol.

You might want to know, Why Safari opens the Maps app and Chrome directs me to a webpage?

Well, because safari is the build in browser made by apple and can detect the URL above. Chrome is "just another app" and must comply to the iOS Ecosystem. Therefor the only way for it to communicate with other apps is by using URL schemes.

Segev
  • 19,035
  • 12
  • 80
  • 152
  • 3
    Well, as I said, the iOS detects the maps:// protocol and Android does open Maps directly via Current Location but using a common Google Maps URL, so what you've said is not quite right.. – Alex Sep 16 '13 at 21:41
4

Simple URL :

https://www.google.com/maps/dir/?api=1&destination=[LAT],[LNG]

This url is specific for routing.

Reference

Martin
  • 628
  • 1
  • 9
  • 28
Khurshid Ansari
  • 4,638
  • 2
  • 33
  • 52
1

I found that this works across the board:

<a href="https://www.google.com/maps/place/1+Fake+Street,+City+Province/State>Get Directions</a>

For desktops/laptops the user has to click Directions when that map loads, but from my testing all mobile devices will load that link in the Google Maps app without difficulty.

1

Based on the documentation the origin parameter is optional and it defaults to the user's location.

... Defaults to most relevant starting location, such as user location, if available. If none, the resulting map may provide a blank form to allow a user to enter the origin....

ex: https://www.google.com/maps/dir/?api=1&destination=Pike+Place+Market+Seattle+WA&travelmode=bicycling

For me this works on Desktop, IOS and Android.

Koni
  • 41
  • 2
0

The URL syntax is the same regardless of the platform in use

String url = "https://www.google.com/maps/search/?api=1&query=" + latitude + ","+ 
longitude;

In Android or iOS the URL launches Google Maps in the Maps app, If the Google Maps app is not installed, the URL launches Google Maps in a browser and performs the requested action.

On any other device, the URL launches Google Maps in a browser and performs the requested action.

here's the link for official documentation https://developers.google.com/maps/documentation/urls/guide

Akshay More
  • 416
  • 4
  • 9
0

The solution I will go with for now due to its simplicity, is to just make 2 buttons, "Apple Maps" and "Google Maps" and let the users decide what they want to use.

This does not really answer the original question, but as I often see that developers tend to make things more difficult than they have to be, I just wanted to add this very simple and stupid approach.

L. Heinrichs
  • 151
  • 1
  • 10
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 26 '23 at 05:44