How to render markers on map fetched from remote backend API?
I am trying to render markers from remote API. I tried fetching data using fetch and tried logging it. I can see it in console log. so how can i use it to render markers on map? remote API is fully functional
fetchData: function(){ fetch("http://www.example.com/endpoint", { method: "POST", body: JSON.stringify({ tag:"get_service_all", lat:"19.34", lon:"72.845", }) }) .then((response) => response.json()) .then((responseData) => console.log(responseData)) .done(); },
and tried mounting it using
componentDidMount: function() { this.fetchData(); }
so how can i setState? does anybody have previous experience on this? Any help is appreciated and thanks alot in advance.
I have some experience. You should put your map in the render() function; and it should look somewhat like this:
<MapView ....>
{this.state.markers.map(marker => {
return (
<MapView.Marker
coordinate={marker.latlng}
/>
);
})}
</MapView>`
then, your getInitialState must be something like
getInitialState() {
return {
markers: []
};
},
and then, once you need to fetch your data (I fetched the data in componentDidMount), after you fetched and have the elements available, you do this:
var elements = elements.map(function(e) {
return {
id: e[0],
latlng: {
latitude: e[2],
longitude: e[3]
}
}
});
this.setState({
markers: elements
});
then, because the state of 'markers' has changed, the render() function will re-render the map, including the markers. For this to work, make sure that your source file is a parsable file (preferably JSON, or you'll need to change some things for this to work) and that it is an array of contents (in my example, it's an array of arrays given my data source specification, but it could also be an array of objects -- you'd just have to change your code a bit)
In the end, for me (I use image markers rather than standard markers), it looks like this:

can you help me with some sample code ?
I think react-native-maps's documentation + my sample code above will help you ;-)
hey @chrisv95 i tried implementing your code. here is the file
var React = require('react'); var ReactNative = require('react-native');
var { Alert, StyleSheet, Dimensions, } = ReactNative;
var MapView = require('react-native-maps'); const windowsWidth = Dimensions.get('window').width; const windowsHeight = Dimensions.get('window').height;
var RanMap = React.createClass({ getInitialState() { return { markers: [] }; },
componentDidMount: function(){ fetch("http://www.example.com/endpoints", { method: "POST", body: JSON.stringify({ tag:"get_service_all", lat:"19.34", lon:"72.845", }) }) .then((response) => response.json()) .then((responseData) => { return responseData }) .done(); },
render() {
var elements = elements.map(function(e) { return { id: e[0], latlng: { latitude: e[2], longitude: e[3] } } }); this.setState({ markers: elements });
var styles = StyleSheet.create({ map: { position: 'absolute', height: windowsHeight/2 + windowsHeight/3, top: 0, left: 0, right: 0, bottom: 0, } });
module.exports = RanMap;
but ran into error cannot read property map of undefined. I also think code need some rectification can you please rectify it for me? thanks
Your code
var elements = elements.map(function(e) {
return {
id: e[0],
latlng: {
latitude: e[2],
longitude: e[3]
}
}
});
this.setState({
markers: elements
});
should be added to the Promise that is returned on fetch(): then(responseData);
then, connect the latitudes & longitudes in your responseData to the mapping by changing elements.map into responseData.map
hey @chrisv95 can you provide me with some tutorial? because i am not getting things right as i am new to react-native .
hey @chrisv95 can you just tell me how can i get rid of the error shown
getInitialState() {
return {
markers: [],
};
},
fetchData: function(){
fetch("http://www.example.com/endpoints, {
method: "POST",
body: JSON.stringify({
tag:"get_service_all",
lat:"19.34",
lon:"72.845",
})
})
.then((response) => response.json())
.then((responseData) => {
this.setState({
markers: responseData.hits.hits.map(function(hit){
const service_location = hit._source.service_location;
return {
latlng: {
latitude: service_location.lat,
longitude: service_location.lon
}
}
})
})
console.log(this.state.markers)
})
here is the render()
{this.state.markers.map(marker => {
return(
<MapView.Marker coordinate={marker.latlng} />
);
})}`
can you help on this?
@sayedatif I think you have to give a key prop for each Markers, usually that's here where you put the id
@KGALLET hey i tried putting ID there but no success the warning still appears in the console
here is the code.
.then((responseData) => {
this.setState({
markers: responseData.hits.hits.map(function(hit){
const service_location = hit._source.service_location;
return {
id: hit._source.service_id,
latlng:{
latitude: service_location.lat,
longitude: service_location.lon
}
}
})
})
can you help me out how to get rid of this warning?
@sayedatif ok so you have the id in the response of your request. Now in the render you have to do something like (according to what you had already done) :
{this.state.markers.map(marker => {
return(
<MapView.Marker coordinate={marker.latlng} key={marker.id} />
);
}
)
}
hey kevin can you help me on this http://stackoverflow.com/questions/38496077/how-can-i-get-markers-within-specific-radius-near-user-current-location-in-react
Im gonna check 👍
EDIT : I don't have Stack Overflow account so I will help u a bit here. If I understand, you have your Markers in the state and you actually want to display markers near the user position.
A solution might be to set the region to the coords of the users, and to put a radius of the distance you want using <MapView.Circle>
For example :
<MapView
ref="map"
showUserLocation={true}
style={styles.map}
region={this.state.region}
>
{this.getMarkers()}
{this.state.markers.map(marker => {
return(
<MapView.Marker coordinate={marker.latlng} image{require('./assets/placeholder-black.png')}/>
);
})}
<MapView.Circle
key={ your_distance }
radius={ your_distance * 1000 }
center={ { latitude: this.state.region.latitude, longitude: this.state.region.longitude } }
/>
</MapView>
And I think that if you don't want the stroke of the circle to appear you can set the strokeColor prop of MapView.Circle to "transparent"
Hope I helped you :)
hey kevin my markers are mounting on app start instead i want only those markers which are near user location or they come inside the radius specified in <MapView.Circle>. I am using ComponentDidMount() which is called after getInitialState() what can i do instead of it?
In your endpoint, do you have any option to set the geoLocation and a radius? This is how I did.
const MyListComponentQuery = container({
variables: (props) => {
return {
after: props.after,
text: props.text,
categories: props.categories,
geoLocation: props.geoLocation,
radius: props.radius,
datesRange: props.datesRange,
dates: props.dates
}
},
query: `
query MyQuery ($after: String, $text: String, $categories: [String],
$geoLocation: String, $radius: Int, $datesRange: [DateTime], $dates: [Date]) {
events: culturalEvents(
first: 30
after: $after
text: $text
categories: $categories
geoLocation: $geoLocation
radius: $radius
datesRange: $datesRange
dates: $dates
sortOn: "start_date"
) {
pageInfo {
endCursor
hasNextPage
}
edges {
node {
${MyItemComponent.getFragment('event')}
}
}
}
}
`,
})(MyListComponent)
I have a prop for radius and one for the geoLocation, that's why I can use the MapView.Circle
yes i have, but i am setting geolocation through componentDidMount() here is my code.
componentDidMount: function() {
this.fetchData();
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
region: {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA
}
});
},
);
}
fetchData: function(){
fetch("http://www.example.com/endpoints", {
method: "POST",
body: JSON.stringify({
tag:"get_service_all",
lat:"19.34",
lon:"72.845",
distance: "3000",
})
})
how can i use it with my code?
Ok so you are supposed to set lat, lon with the user location and distance with the radius you want too, in order to only get "markers" near the user position. :)
so how can i do it? i want only those marker which are near user but my markers are getting rendered even if they are not in the specified radius you can see the image

I think the problem is your request... I can't help you more since I don't have access to your endpoint :/
hey kevin can i comment my api here so that you get some idea?
hey @KGALLET can you help me on this http://stackoverflow.com/questions/38524371/i-am-trying-to-get-markers-near-user-location-by-calculating-distance-using-have