How to create a link that opens the appropriate map app on any device, with directions to the destination with JavaScript?

Spread the love

To create a link that opens the appropriate map app on any device, with directions to the destination with JavaScript, we create a JavaScript function to detect the platform.

For instance, we write

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

to add a link that calls myNavFunc when we click it.

Then we write

function myNavFunc() {
  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]"
    );
}

to get the platform with navigation.platform.

We call window.open with the URL of the map to open the map according to the platform.

Leave a Reply

Your email address will not be published. Required fields are marked *