简体   繁体   中英

How do I set a marker in MapView of React Native

  • I want to set a marker on MapView in React Native, but I can't find any information through official documents of MapView .
  • If it is not allowed in that way, how can I use existed react module such as react-googlemaps in React Native?

Thank you @naoufal. Finally I am able to display markers on map for react native IOS.

<View style={styles.container}>
        <MapView style={styles.map}
          initialRegion={{
              latitude: 37.78825,
              longitude: -122.4324,
              latitudeDelta: 0.0,
              longitudeDelta: 0.0,
          }}
        >
        <MapView.Marker
            coordinate={{latitude: 37.78825,
            longitude: -122.4324}}
            title={"title"}
            description={"description"}
         />
      </MapView>
 </View>

For map and container styles, I have used following styles:

 var styles = StyleSheet.create({

  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
    map: {
      position: 'absolute',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
    }
});

I have referred following link: React native IOS- Display Markers on map

You can set markers using the annotations prop.

For example:

var markers = [
  {
    latitude: 45.65,
    longitude: -78.90,
    title: 'Foo Place',
    subtitle: '1234 Foo Drive'
  }
];

<MapView
  region={...}
  annotations={markers}
/>
import MapView, { Marker } from 'react-native-maps';

<View>
    <MapView
    style={styles.mapStyle}
    initialRegion={{
    latitude: 37.78825,
    longitude: -122.4324,
    latitudeDelta: 0.0922,
    longitudeDelta: 0.0421,
    }}
    >
        <Marker coordinate = {{latitude: 37.78825,longitude: -122.4324}}
         pinColor = {"purple"} // any color
         title={"title"}
         description={"description"}/>
    </MapView>
</View>

For those looking for a dynamic (eg, from API), rather than hardcoded coordinates; here's the copy/paste snippet from one of the screens automatically generated by Expo CLI , included React Hooks :

import axios from "axios";
import MapView from "react-native-maps";
import { Dimensions, StyleSheet } from "react-native";
import { Marker } from "react-native-maps";
import { Text, View } from "../components/Themed";

export default function TabTwoScreen() {
  const [markers, setMarkers] = useState(null);

  useEffect(() => {
    axios({
      method: "GET",
      url: "https://API_URL...",
      headers: {
        Authorization: `Bearer MY_TOKEN_ABC123...`,
        Accept: "application/json",
      },
    })
      .then((response) => {
        setMarkers(response.data.results);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []); // "[]" makes sure the effect will run only once.

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Tab Two</Text>
      <MapView style={styles.map}>
        {markers &&
          markers.map((marker: any, index: number) => (
            <Marker
              key={index}
              coordinate={{
                latitude: marker.location[1],
                longitude: marker.location[0],
              }}
              title={marker.title}
              description={marker.description}
            />
          ))}
      </MapView>
    </View>
  );
}

const styles = StyleSheet.create({
  // Add your styles here...
});

Updated code - 2020 | React Native 0.63

import MapView, { Marker } from "react-native-maps";
<MapView
    style={styles.mapStyle}
    region={{
        latitude: this.state.mapLat,
        longitude: this.state.mapLong,
        latitudeDelta: 0.001663,
        longitudeDelta: 0.002001,
            }}
        onRegionChangeComplete={this.onRegionChange}
>
    <Marker
        coordinate={{latitude: 51.5078788, longitude: -0.0877321}}
    >
    </Marker>
</MapView>

According to this issue , it's not exposed yet. You won't be able to use the web-React package either, React Native doesn't work like that.

Two suggestions:

  1. Wait for the above issue to be resolved to get a proper API
  2. Try and use WebView to link to a Google Map with an annotation

I'm not actually certain whether #2 is possible though.

import MapView from 'react-native-maps';
<View style={StyleSheet.absoluteFillObject}>
        <MapView style={styles.map}
          showsUserLocation //to show user current location when given access
          loadingEnabled //to show loading while map loading
          style={styles.map}
          initialRegion={{
              latitude,
              longitude,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
          }}
        >
        {

             locations && locations.map((location, index) => {
                   const {
                       coords: { latitude, longitude }
                          } = location;
                                return (
                                    <MapView.Marker
                                        key={index}
                                        coordinate={{ latitude, longitude }}
                                        title={"title"}
                                        description={"address"}
                                        // onPress={this.onMarkerPress(location)}
                                    />
                                )
                            })
                        }
      </MapView>
 </View>```

const styles = StyleSheet.create({

map: {
  position: 'absolute',
  top: 0,
  left: 0,
  right: 0,
  bottom: 0,
}

});


"dependencies": { "native-base": "^2.13.8", "react": "16.9.0", "react-native": "0.61.2", "react-native-maps": "git+ https://git@github.com/react-native-community/react-native-maps.git " },


Try using this. Hope it helps to mark for many locations. Happy Coding.

Thank you @zia_qureshi. Finally I am able to display markers on map for react native android.

 import MapView, { Marker } from "react-native-maps"; const App = () => { const [region, setRegion] = useState({ latitude: 51.5078788, longitude: -0.0877321, latitudeDelta: 0.009, longitudeDelta: 0.009 }); return ( <MapView style={{ flex: 1 }} region={region} onRegionChangeComplete={region => setRegion(region)} > <Marker coordinate={{ latitude: 51.5078788, longitude: -0.0877321 }} /> </MapView> ); }; export default App;

You can try webview for that-

var html = '<!DOCTYPE html><html><body><div "class="google-maps"
style="position:absolute; bottom:0px; overflow:hidden; height:100%; left:0px; width:100%"><iframe frameborder="0" width="100%" height="120%" style="margin-top:-30%;"  scrolling="no" src="https://www.google.com/maps/embed/v1/place?key=yourKEY &q=Space+Needle,Seattle+WA" allowfullscreen> </iframe> </google-maps></body></html>';
return (
<View style={styles.container}>
  <WebView html={html}/>
</View>

Can use markers and other options. Hope it will help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM