Search code examples
react-nativegoogle-mapsgoogle-maps-markersreact-native-maps

Get title and location where marker points in react-native-maps


I want to get title and description every time user points to a certain location. How can I set title and description prop of particular location by using states?

const AddLocation=()=>{
return (
    <View style={styles.container}>
        
    <MapView style={styles.map}
     initialRegion={{
        latitude:  33.738045,
        longitude: 73.084488,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        }}>
        <Marker coordinate = {{latitude:  33.738045,longitude: 73.084488}}
     pinColor = {"red"} 
     title={"title"}
     description={"description"}/>
    </MapView>
        
    </View>
)
}

Solution

  • You can use the useState of react. Below is a code snippet of the sample code showing how you can do this.

    import React, {useState} from 'react';
    import { Text, View, StyleSheet, Dimensions } from 'react-native';
    import MapView, { Marker } from 'react-native-maps';
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
      },
      map: {
        width: Dimensions.get('window').width,
        height: Dimensions.get('window').height,
      },
    });
    
    const AddLocation = () => {
    const [title, setTitle] = useState("Title");
    const [desc, setDesc] = useState("this is Description");
        return (
          <View style={styles.container}>
            <MapView
              style={styles.map}
              initialRegion={{
            latitude:  33.738045,
            longitude: 73.084488,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
            }}>
              <Marker coordinate = {{latitude:  33.738045,longitude: 73.084488}}
         pinColor = {"red"} 
         title={title}
         description={desc}/>
            </MapView>
          </View>
        );
      }
    
    
    export default AddLocation;