[android] How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

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 )

This question is related to android html ios google-maps mobile

The answer is


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.


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>

Simple URL :

https://www.google.com/maps/dir/?api=1&destination=lat,lng

This url is specific for routing.

Reference : https://developers.google.com/maps/documentation/urls/guide#directions-action


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.


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


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);
   }
 });
 });
 }

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.


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


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


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to google-maps

GoogleMaps API KEY for testing Google Maps shows "For development purposes only" java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion How to import JSON File into a TypeScript file? Googlemaps API Key for Localhost Getting "Cannot call a class as a function" in my React Project ERROR: Google Maps API error: MissingKeyMapError This page didn't load Google Maps correctly. See the JavaScript console for technical details Google Maps API warning: NoApiKeys ApiNotActivatedMapError for simple html page using google-places-api

Examples related to mobile

How to center a component in Material-UI and make it responsive? NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference Asus Zenfone 5 not detected by computer background: fixed no repeat not working on mobile Check box size change with CSS onClick not working on mobile (touch) Sharing link on WhatsApp from mobile website (not application) for Android Bootstrap 3 Slide in Menu / Navbar on Mobile How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place? Using form input to access camera and immediately upload photos using web app