open maps/google maps in react native
Asked Answered
D

19

84

I am trying to open google maps or maps in my react-native application.

When I run the app on my iPhone/simulator, I receive this error

"Don't know how to open URI:...".

What I am doing wrong?

My code:

    openGps() {
      var url = 'geo:37.484847,-122.148386'
      this.openExternalApp(url)
    }
    
    openExternalApp(url) {
      Linking.canOpenURL(url).then(supported => {
        if (supported) {
          Linking.openURL(url);
        } else {
          console.log('Don\'t know how to open URI: ' + url);
        }
      });
    }
Drayton answered 4/4, 2017 at 17:38 Comment(1)
is there a similar way to open camera app?Acutance
T
264

To open url with custom label ios/android:

const scheme = Platform.select({ ios: 'maps://0,0?q=', android: 'geo:0,0?q=' });
const latLng = `${lat},${lng}`;
const label = 'Custom Label';
const url = Platform.select({
  ios: `${scheme}${label}@${latLng}`,
  android: `${scheme}${latLng}(${label})`
});

    
Linking.openURL(url);
Translative answered 28/12, 2017 at 11:36 Comment(13)
This solution is so clean! Thank you for the label component!Ul
change like this const scheme = Platform.OS === 'ios' ? 'maps:0,0?q=' : 'geo:0,0?q=';Sunday
on google maps the marker's name is the coordinates and not the label :/Cohort
is it possible to add custom label to android?Interchange
There's a nice library to do all of this and more: github.com/tschoffelen/react-native-map-link.Knave
scheme is in wrong format. You have to replace zeroS with lat and lon. This way it produces "geo:0,0?q=41.04481,28.9976903(address)". lat and lon should be on the point at zeroSPush
how to sent a source and destination with navigation on,the above answer is correct,it does the functionalityKillerdiller
can i give params like i need to show my map on driving mode not on walking mode ? @Narek GhazaryanShayne
is there a way to show the direction name on google maps instead of the coordinates, at least on ios, you can show the custom label but on android it doesn't seem to work?Goldagoldarina
I had to do label = encodeURIComponent(label) to support spaces on iOSWina
I just wanted to mention that this code broke for iOS after updating to RN 0.71.7 and I was able to fix the issue by adding // to ios: 'maps://0,0?q='Pellmell
@Pellmell Came here for the same issue, thanks for this it was a lifesaver!Cockloft
@Pellmell Thanks!! It was breaking in ios without // and adding ios: 'maps://0,0?q=' works perfectAbm
S
27
const url = Platform.select({
  ios: `maps:0,0?q=${fullAddress}`,
  android: `geo:0,0?q=${fullAddress}`,
})

Linking.openURL(url)
Subacid answered 10/2, 2020 at 14:22 Comment(2)
I'd excuse @pragnesh for this - it's a clean, self-explanatory and actually working code.Impuissant
too easy! so clean @SubacidSeyler
U
25

you can do like this:

Android:

 <TouchableOpacity onPress={() => Linking.openURL('google.navigation:q=100+101')}>

where q is the destination lat + long

IOS:

  <TouchableOpacity onPress={() => Linking.openURL('maps://app?saddr=100+101&daddr=100+102')}>

where saddr is start address and daddr is destination address lat+long

Undersize answered 10/4, 2018 at 19:50 Comment(3)
Ref: developers.google.com/maps/documentation/urls/…Zavala
Thanks, DEV for the solution!Transponder
Basically you can add just daddr for IOS. This might be taken your current location and directing you to daddr location. Thanks for answer btw! <3Milliliter
U
23

This is because iOS does not yet have support for geo: yet as mentioned in this SO answer. What you can do is detect the OS and:

  • use geo: on Android
  • handle iOS differently. Possibly use maps: as it will open up Apple Maps, though I'm unsure how to properly send the coordinates to it. Or maybe append it to a google maps HTTP URL and open it in the browser.

For example, your openGps function could look like this:

openGps = (lat, lng) => {
  var scheme = Platform.OS === 'ios' ? 'maps:' : 'geo:';
  var url = scheme + `${lat},${lng}`;
  Linking.openURL(url);
}
Uther answered 4/4, 2017 at 23:45 Comment(1)
You can also use http://maps.apple.com/?ll=<lat>,<long> or http://maps.apple.com/?daddr=<lat>,<long> to start a navigation.Bushwhack
K
14
const latitude = "40.7127753";
const longitude = "-74.0059728";
const label = "New York, NY, USA";

const url = Platform.select({
  ios: "maps:" + latitude + "," + longitude + "?q=" + label,
  android: "geo:" + latitude + "," + longitude + "?q=" + label
});
Linking.openURL(url);

or with checking if there's a google map app on device and if not open the location in browser

const latitude = "40.7127753";
const longitude = "-74.0059728";
const label = "New York, NY, USA";

const url = Platform.select({
  ios: "maps:" + latitude + "," + longitude + "?q=" + label,
  android: "geo:" + latitude + "," + longitude + "?q=" + label
});

Linking.canOpenURL(url).then(supported => {
  if (supported) {
    return Linking.openURL(url);
  } else {
    const browser_url =
      "https://www.google.de/maps/@" +
      latitude +
      "," +
      longitude +
      "?q=" +
      label;
    return Linking.openURL(browser_url);
  }
});
Khat answered 4/2, 2019 at 10:58 Comment(2)
With this answer the map opens along with custom label which is a good thing. But a major issue in this approach is that if I have multiple addresses with same block names in different cities then no matter which lat long I provide, it always takes me to the first city with the given block name. If there is a fix for that then this would be a good solution.Loganiaceous
This just search apple maps and google maps for the label and ignores the coordinates.Wina
T
10

Working on Android with an address using the following:

Linking.openURL('https://www.google.com/maps/search/?api=1&query=address');

Replace address with your favourite address.

Theomancy answered 23/5, 2019 at 17:9 Comment(0)
B
5

To complement other answers, here's a snippet of adding a marker on Android:

    const location = `${latitude},${longitude}`
    const url = Platform.select({
      ios: `maps:${location}`,
      android: `geo:${location}?center=${location}&q=${location}&z=16`,
    });
    Linking.openURL(url);

If you want more details about Android and google maps, here's the link for the documentation: https://developers.google.com/maps/documentation/urls/android-intents

Boatswain answered 10/10, 2019 at 5:6 Comment(0)
T
5

I've tried this solution and it's working

const scheme = Platform.select({ ios: 'maps:0,0?q=', android: 'geo:0,0?q=' });
const latLng = `${lat},${lng}`;
const label = 'Custom Label';
const url = Platform.select({
  ios: `${scheme}${label}@${latLng}`,
  android: `${scheme}${latLng}(${label})`
});

Linking.openURL(url);

Tympany answered 18/8, 2020 at 10:13 Comment(2)
Where is the difference to this already given answer (https://mcmap.net/q/239889/-open-maps-google-maps-in-react-native)?Iseult
I don't have the right to upvote it because I'm new that's why I did this to let them know it is workingTympany
M
4

With the help of oma's answer, I came up with this. For the ios version, I directly wrote googleMaps instead of maps because it did not work. This is given that Google Maps is installed on the device and I tested this with a physical device. If its not installed it will go into the store. It works perfectly while starting the navigation too.

<Button
  hasText
  transparent
  onPress={() =>
    Linking.openURL(
      Platform.OS === 'ios'
        ? 'googleMaps://app?saddr=6.931970+79.857750&daddr=6.909877+79.848521'
        : 'google.navigation:q=6.909877+79.848521',
    )
 }>
    <Text>Open Maps</Text>
 </Button>

FYI - Im using the Button component from the Native Base library.

Moonshine answered 25/10, 2020 at 19:52 Comment(2)
How can I add more location to ios url? there is "waypoints" to redirect to browser but its not working for redirecting to appSeaddon
one problem here is that on ios the from and the to coordinates are the sameRedbud
S
4

For apple maps direction with coordinate like this

Linking.openURL(`maps://app?daddr=${latitude},${longitude}&dirflg=d&t=m`)

dirflg = The transport type.

  1. d (by car)
  2. w (by foot)
  3. r (by public transit)

t = map type m standart view

daddr = destination address

enter image description here

Shum answered 31/1, 2023 at 21:49 Comment(0)
T
3

From the documentation in Apple Map Links, a little changes from @Narek Ghazaryan's answer. This is due to apple maps will query on provided "label" first. If the label or store name do not exist, it will show nothing.

So we need to add a parameter as "ll" to specify current location with the provided label / store name.

const scheme = Platform.select({ ios: 'maps:0,0?q=', android: 'geo:0,0?q=' });
const latLng = `${lat},${lng}`;
const label = 'Custom Label';
const url = Platform.select({
  ios: `${scheme}${label}&ll=${latLng}`,
  android: `${scheme}${latLng}(${label})`
});
Teece answered 6/3, 2020 at 9:43 Comment(0)
S
3

One solution is to use react-native-map-link lib. It opens a bottom sheet with desired options

import { showLocation } from 'react-native-map-link'

showLocation({
    latitude: 38.8976763,
    longitude: -77.0387185,
    sourceLatitude: -8.0870631,  // optionally specify starting location for directions
    sourceLongitude: -34.8941619,  // not optional if sourceLatitude is specified
    title: 'The White House',  // optional
    googleForceLatLon: false,  // optionally force GoogleMaps to use the latlon for the query instead of the title
    googlePlaceId: 'ChIJGVtI4by3t4kRr51d_Qm_x58',  // optionally specify the google-place-id
    alwaysIncludeGoogle: true, // optional, true will always add Google Maps to iOS and open in Safari, even if app is not installed (default: false)
    dialogTitle: 'This is the dialog Title', // optional (default: 'Open in Maps')
    dialogMessage: 'This is the amazing dialog Message', // optional (default: 'What app would you like to use?')
    cancelText: 'This is the cancel button text', // optional (default: 'Cancel')
    appsWhiteList: ['google-maps'] // optionally you can set which apps to show (default: will show all supported apps installed on device)
    // appTitles: { 'google-maps': 'My custom Google Maps title' } // optionally you can override default app titles
    // app: 'uber'  // optionally specify specific app to use
})
Striper answered 4/6, 2020 at 18:25 Comment(0)
A
3

For google map/Map direction, you can use this code

const latitude = "30.3753";
const longitude = "69.3451";
const openMapDirection = () => {
    const url: any = Platform.select({
      ios: `comgooglemaps://?center=${latitude},${longitude}&q=${latitude},${longitude}&zoom=14&views=traffic"`,
      android: `geo://?q=${latitude},${longitude}`,
    });
    Linking.canOpenURL(url)
      .then((supported) => {
        if (supported) {
          return Linking.openURL(url);
        } else {
          const browser_url = `https://www.google.de/maps/@${latitude},${longitude}`;
          return Linking.openURL(browser_url);
        }
      })
      .catch(() => {
        if (Platform.OS === 'ios') {
          Linking.openURL(
            `maps://?q=${latitude},${longitude}`,
          );
        }
      });
  };

Note: For open google map on IOS you have to add this in info.plist

<key>LSApplicationQueriesSchemes</key>
  <array>
   <string>comgooglemaps</string>
  </array>
Announcement answered 11/6, 2021 at 15:0 Comment(1)
Hi, i tried your solution and i keep getting Unsupported linkRedbud
R
2

I think react-native-launch-navigator module is a much cleaner way of doing this. Then it is simple as LaunchNavigator.navigate([50.279306, -5.163158], {start: "50.342847, -4.749904"}) .then(() => console.log("Launched navigator")) .catch((err) =>console.error("Error launching navigator: "+err));.

Rifling answered 17/3, 2020 at 4:45 Comment(0)
O
2

I found this to be the easiest way to navigate from your app to Google Maps

const url = `https://www.google.com/maps/dir/?api=1&destination=lat,long&dir_action=navigate`
Linking.openURL(url);
Oratorio answered 7/11, 2021 at 15:8 Comment(0)
R
2

I have created a separate component for store location and full code is as under.

Component code:

import React from "react";
import { View, Pressable, Platform, Linking } from "react-native";
import styles from "./styles";
import Text from "../Text";

const StoreLocation = ({}) => {

  /**
   * method to open google map
   */
  const openMap = () => {
    const latitude = 33.189368147027565; // latitude of your desire location
    const longitude = 73.35574341458842; // longitude of your desire location
    const scheme = Platform.select({
      ios: "maps:0,0?q=",  // if device is ios 
      android: "geo:0,0?q=", // if device is android 
    });
    const latLng = `${latitude},${longitude}`;
    const label = "your own label";
    const url = Platform.select({
      ios: `${scheme}${label}@${latLng}`,
      android: `${scheme}${latLng}(${label})`,
    });

    Linking.openURL(url);
  };

  return (
    <Pressable onPress={() => openMap()} style={styles.mapView}>
      <View>
        <Text>Open Map</Text>
      </View>
    </Pressable>
  );
};

export default StoreLocation;

if you only want to use method just copy openMap() method and change your desired longitude, latitude & label to use this method according to your app.

tested on Android

Rodrigo answered 2/8, 2022 at 9:50 Comment(0)
A
1

you can also use this solution

Linking.openURL(`https://www.google.com/maps/dir/?api=1&origin=${startPlace.latitude},${startPlace.longitude}&destination=${endPlace.latitude},${endPlace.longitude}`)

reference: https://developers.google.com/maps/documentation/urls/get-started#map-action

Addax answered 11/12, 2022 at 18:27 Comment(0)
L
1
> enter code hereconst location = `${latitude},${longitude}`
>       const url = Platform.select({
>      // YOU CAN CHECK FOR IOS ASWELL
>         android: `geo:${location}?center=${location}&q=${location}&z=16`,
>       });
>       Linking.openURL(url);
Lusty answered 18/12, 2023 at 19:6 Comment(0)
R
-2

This Will work....

const lat = "12.914490",
const lng = "77.666512",
const lable = "Any Title",

const scheme = Platform.OS === "android" ? "geo:0,0?q=" : "maps:0,0?q=";
var latLng = `${lat},${lng}`;
var label = lable;

const url = Platform.select({
   ios: `${scheme}${label}@${latLng}`,
   android: `${scheme}${latLng}(${label})`,
});

console.log(url)
Reader answered 6/2, 2023 at 8:3 Comment(1)
Downvoted just because its the same as the other answers only a bit less cleanSlaughter

© 2022 - 2025 — McMap. All rights reserved.