react-native-maps icon indicating copy to clipboard operation
react-native-maps copied to clipboard

How to render markers on map fetched from remote backend API?

Open sayedatif opened this issue 10 years ago • 27 comments

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.

sayedatif avatar Jul 12 '16 08:07 sayedatif

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:

image

christianversloot avatar Jul 12 '16 10:07 christianversloot

can you help me with some sample code ?

sayedatif avatar Jul 12 '16 11:07 sayedatif

I think react-native-maps's documentation + my sample code above will help you ;-)

christianversloot avatar Jul 12 '16 11:07 christianversloot

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() { {this.state.markers.map(marker => { return ( <MapView.Marker coordinate={marker.latlng} /> ); }) } } })

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

sayedatif avatar Jul 12 '16 12:07 sayedatif

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

christianversloot avatar Jul 12 '16 14:07 christianversloot

hey @chrisv95 can you provide me with some tutorial? because i am not getting things right as i am new to react-native .

sayedatif avatar Jul 13 '16 06:07 sayedatif

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} />
            );
          })}`

mapserror can you help on this?

sayedatif avatar Jul 14 '16 13:07 sayedatif

@sayedatif I think you have to give a key prop for each Markers, usually that's here where you put the id

KGALLET avatar Jul 15 '16 20:07 KGALLET

@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 avatar Jul 21 '16 06:07 sayedatif

@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} />
            );
          }
     )
}

KGALLET avatar Jul 21 '16 07:07 KGALLET

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

sayedatif avatar Jul 21 '16 07:07 sayedatif

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 :)

KGALLET avatar Jul 21 '16 07:07 KGALLET

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?

sayedatif avatar Jul 21 '16 08:07 sayedatif

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

KGALLET avatar Jul 21 '16 08:07 KGALLET

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?

sayedatif avatar Jul 21 '16 08:07 sayedatif

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. :)

KGALLET avatar Jul 21 '16 08:07 KGALLET

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 img-20160721-wa0002_1469091349918

sayedatif avatar Jul 21 '16 08:07 sayedatif

I think the problem is your request... I can't help you more since I don't have access to your endpoint :/

KGALLET avatar Jul 21 '16 09:07 KGALLET

hey kevin can i comment my api here so that you get some idea?

sayedatif avatar Jul 21 '16 14:07 sayedatif

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

sayedatif avatar Jul 22 '16 10:07 sayedatif