React Native Maps: Multiple Markers placed and state changed - react-native

I am currently working on an application that uses React Native Maps. I've seen their examples for putting multiple markers and how to change a marker's state when pressed, and I would like to be able to combine the two functions together. I want to be able to put down multiple markers, then change the state of individual markers when pressed. I've had success putting down multiple markers, but when pressed, all markers have their state changed. I'd like to know what to do so markers will have individual states changed when pressed. Thanks for all the help.
Here are the links to the examples of React Native Maps I used:
https://github.com/airbnb/react-native-maps/blob/master/example/examples/DefaultMarkers.js
https://github.com/airbnb/react-native-maps/blob/master/example/examples/MarkerTypes.js
Here's the code I currently have
const SPACE = 0.01;
let id = 0;
class MarkerTypes extends React.Component {
constructor(props) {
super(props);
this.state = {
marker1: true,
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
markers: [],
};
}
onMapPress(e) {
console.log(e)
this.setState({
markers: [
...this.state.markers,
{
coordinate: e.nativeEvent.coordinate,
key: id++,
marker1: true,
},
],
});
}
render() {
return (
<View style={styles.container}>
<MapView
provider={this.props.provider}
style={styles.map}
initialRegion={this.state.region}
onPress={(e) => this.onMapPress(e)}
>
{this.state.markers.map(marker => (
<MapView.Marker
key={marker.key}
})}
onPress={() => {
this.setState({ marker1: !this.state.marker1 })}
}
coordinate={marker.coordinate}
image={this.state.marker1 ? flagBlueImg : flagPinkImg}
>
</MapView.Marker>
))}
</MapView>
</View>
);
}
}

To change the image marker on the marker that is touched on the map you need to toggle the marker property on the marker inside the this.state.markers array, eg this.state.markers[0].marker1, currently you are toggling the this.state.marker1 which is shared by all markers
{this.state.markers.map((marker, index) => (
<MapView.Marker
key={marker.key}
onPress={() => {
const marker = this.state.markers[index]
marker.marker1 = !marker.marker1
this.setState({ markers: [
...this.state.markers.slice(0, index),
marker,
...this.state.markers.slice(index + 1)
]})}
}
coordinate={marker.coordinate}
image={marker.marker1 ? flagBlueImg : flagPinkImg}
>
</MapView.Marker>
))}
in this way each marker is using and updating it's own state in the array.

Related

How to print latitude by button in react native maps?

I use DefaultMarkers to get location from user.
I have a button and a function. In the function I use a code to show latitude in console. Now When I press the button, in console not happening but for second press I can see latitude in console.
If I change location and try again, I should press button for twice to see latitude in console.
constructor(props){
super(props);
this.state={
markers: [],
}
}
onMapPress(e) {
this.setState({
markers: [
{
coordinate: e.nativeEvent.coordinate,
key: 0,
},
],
});
}
SaveAddress=()=>{
console.log(JSON.stringify(this.state.markers[0].coordinate.latitude);
}
<Button onPress={this.SaveAddress}>
<Text>Save</Text>
</Button>
<MapView
style={styles.map}
initialRegion={{
latitude: 28.95761453,
longitude: 50.83710976,
latitudeDelta: 0.0040,
longitudeDelta: 0.0040,
}}
provider={this.props.provider}
onPress={(e) => this.onMapPress(e)}
>
{this.state.markers.map(marker => (
<Marker
key={marker.key}
coordinate={marker.coordinate}
/>
))}
</MapView>
Because, when you first-time press that button to execute this function
SaveAddress=()=>{console.log(JSON.stringify(this.state.markers[0].coordinate.latitude);}
The state is empty so you don't get any value. On your first press, it just starts to save the state and start to render. But on your second press, rendering is complete and the states became set then you got the value.
You can do instead
import React, { Component } from 'react';
import { View, Text, TouchableOpacity, WebView, StyleSheet,KeyboardAvoidingView, ActivityIndicator,Platform,TextInput,Dimensions} from 'react-native'
import MapView, { PROVIDER_GOOGLE, Region,Marker } from 'react-native-maps';
export default class App extends React.Component {
constructor(props){
super(props);
this.state={
markers: [
{
coordinate: { latitude: 28.95761453,
longitude: 50.83710976,
},
key: 0,
},
],
}
}
onMapPress(e) {
this.setState({
markers: [
{
coordinate: e.nativeEvent.coordinate,
key: 0,
},
],
});
}
SaveAddress=()=>{
console.log(JSON.stringify(this.state.markers[0].coordinate.latitude))
}
render() {
return (
<View style={{flex:1}}>
<MapView
style={[styles.map]}
initialRegion={{
latitude: 28.95761453,
longitude: 50.83710976,
latitudeDelta: 0.0040,
longitudeDelta: 0.0040,
}}
// onMapReady={this.onMapReady}
provider={ PROVIDER_GOOGLE}
onPress={(e) => this.onMapPress(e)}
>
{this.state.markers.map(marker => (
<Marker
key={marker.key}
coordinate={marker.coordinate}
/>
))}
</MapView>
<TouchableOpacity onPress={()=>this.SaveAddress()}>
<Text>Save</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
map: {
...StyleSheet.absoluteFillObject,
},
});

How to refresh the map in react-native-maps?

I used react-native-maps in my location tracking application. And now i want to clear ( refresh ) the map with all the markers and poly-lines without refreshing react component , when user stop the location Tracking ( using a button ).Is there any way to do that?
At some point if you wish to change what is visible on your component in react, there's no other way than rerendering your component.
I do not know react-native-maps, but I think this problem can be solved using general react knowledge.
Markers and polygons in react-native-maps are added as children of the MapView, so depending on how you are storing your markers/lines, you should be able to simply rely on react's state or props changes to update your MapView.
For example, if your markers are stored in your component's state, you could do something like this:
class MyLocationTracker extends React.Component {
state = { markers: [{ latlng: { latitude: 1, longitude: 1 } }] }
render = () => {
return (
<View>
<Text onPress={() => this.setState({ markers: [] })}>Reset markers</Text>
<MapView>
{this.state.markers.map((marker) => <Marker coordinate={marker.latlng} />)}
</MapView>
</View>
)
}
}
When the state changes, react will call the render() function again and update the markers. Note that this will also serenader the <MapView /> component.
If you wish to avoid rerendering the <MapView /> component, you can move the logic to a new component that will handle the markers only, like so:
class MyLocationTracker extends React.Component {
render = () => {
return (
<View>
<Text onPress={this.markers.reset}>Reset markers</Text>
<MapView>
<MyMarkers ref={(comp) => { this.markers = comp }} />
</MapView>
</View>
)
}
}
class MyMarkers extends React.Component {
state = { markers: [{ latlng: { latitude: 1, longitude: 1 } }] }
reset = () => {
this.setState({ markers: [] })
}
render = () => {
return (
<View>
{this.state.markers.map((marker) => <Marker coordinate={marker.latlng} />)}
</View>
)
}
}
Again, changes in the state would trigger a rerender of your component. But now, since only <MyMarkers />'s state changes, it will rerender itself but not anything else.
I hope that helps :)

Is it possible to change MapView Market pinColor programatically by clicking any button?

I have implemented a MapView with react-native-maps. I'm trying to change Marker's pinColor by clicking on it.
Note: I have large amounts of markers. So I don't think refreshing all view can be a good solution. I need directly change the selected marker's color.
I didn't find how to do it. I tried below code:
class TestMap extends React.Component {
constructor(props) {
this.state = {
testColor: "#FFFFFF",
userLatitude:0,
userLongitude:0,
data:[]
}
}
render() {
return (
<MapView
provider={PROVIDER_GOOGLE}
showsTraffic={true}
showsBuildings={true}
toolbarEnabled={true}
loadingEnabled={true}
style={styles.map}
initialRegion={{
latitude: this.state.userLatitude,
longitude: this.state.userLongitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA
}}
onPoiClick={this.onPoiClick}
showsUserLocation={true}
followsUserLocation={true}
showsMyLocationButton={true}
loadingBackgroundColor="#FEA405"
loadingIndicatorColor="white"
onLongPress={e => this.onMapPress(e)}
enableZoomControl
>
{this.ListMarkers()}
</MapView>
)};
ListMarkers() {
return this.state.data.map((data, i) => {
return (
<Marker
key={i}
onPress={e => this.onPressMarker(e, i, data)}
coordinate={{
longitude: data.LONGITUDE,
latitude: data.LATITUDE
}}
pinColor={this.state.testColor}
/>
)}
)};
onPressMarker(e, index, data) {
this.setState({testColor:"#000000"});
}
}
I expect the color of marker should change after clicking on it but it is not working.
Thanks for your help.
You can set the selected pin in the state and use a different style in that case, if you have some id in your data you can use that value instead of the index:
constructor(props) {
this.state = {
selectedPin: -1,
}
}
ListMarkers = () => {
return this.state.data.map((data, i) => {
return (
<Marker
key={i}
onPress={e => this.onPressMarker(e, i, data)}
coordinate={{
longitude: data.LONGITUDE,
latitude: data.LATITUDE
}}
pinColor={ i === this.state.selectedPin ? '#FF0000' : '#FFFFFF'}
/>
)}
)};
onPressMarker = (e, index, data)=> {
this.setState({selectedPin:index});
}

React Native Maps animate to bearing after initial render

I am trying to call a method on the map right after the component first renders. In this case this.map is undefined, but shouldn't it be set by the ref? How do I get a reference to the MapView in the componentDidMount method?
import React from 'react';
import { MapView } from 'expo';
export default class Map extends React.Component {
componentDidMount() {
this.map.animateToBearing(25)
}
render() {
return (
<MapView
ref={ref => { this.map = ref }}
style={{ flex: 1 }}
mapType="satellite"
initialRegion={{
latitude: 39.2741004,
longitude: -76.6502307,
latitudeDelta: 0.002,
longitudeDelta: 0.001,
}}
/>
);
}
}
Looking at this Github issue, you probably have to use onLayout instead of componentDidMount.
For example:
<MapView
ref={ref => { this.map = ref }}
onLayout={() => this.map.animateToBearing(25)}
....
/>
const [heading, setHeading] = useState(0);
const cameraView = {
center: {
latitude: lat,
longitude: lng,
},
pitch: 10,
heading: heading,
altitude: 1,
zoom: 15
};
let getHeading = () => {
Location.watchHeadingAsync(value => {
setHeading(value.magHeading)
});
};
useEffect(()=>{
initialLocation();
getHeading();
}, [])
By using watchHeadingAsync you can update the heading constantly.

Remove marker from google map in react native

Is possible to remove marker from map view? How to remove marker from google map view. I using "react-native-maps" display google map.
Please Help.
To be able to remove or add markers, you just need to do this
//Note : my map markers is => this.props.markers
componentDidMount() {
this.renderMarkers(this.props.markers)
}
async renderMarkers(mapMarkers) {
let markers = [];
markers = mapMarkers.map(marker => (<Marker
key={marker.code}
coordinate={{latitude: marker.lat, longitude: marker.lng}}
onPress={{}}
/>)
);
this.setState({markers});
}
refreshMarkers() {
this.renderMarkers(this.props.markers).then(() => {
this.forceUpdate();
});
}
render() {
return (
<MapView
ref={(ref) => this.mapView = ref}
style={styles.map}
region={this.props.coordinate}
>
{this.state.markers}
</MapView>
);
}
Here's how I do it.
Essentially, you need to keep an array of markers in the state, then remove the marker you want to delete from the state.
I store the list of markers in the state like so:
this.state = {
markers: [],
};
When you actually create the markers, you pass the index in the function that will remove the marker from the state. In this case onMarkerPress(index)
createMarkers() {
return this.state.markers.map((marker, index) => (
<Marker
draggable
onPress={event => this.onMarkerPress(index)}
key={index}
coordinate={{
latitude: parseFloat(marker.latitude),
longitude: parseFloat(marker.longitude),
}}
/>
));
}
Here's the onMarkerPress function:
onMarkerPress(index) {
this.state.markers.splice(index, 1);
this.setState({markers: this.state.markers});
}
And finally, you map component will look like this:
<MapView
style={styles.map}
mapType={'satellite'}
provider={PROVIDER_GOOGLE}
initialRegion={{
latitude: 45.50235905860018,
longitude: -73.60357092645054,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
onLongPress={e => this.addNewMarker(e)}>
{this.createMarkers()}
</MapView>
And that's it!