0
I’m creating a google maps heat map with reactjs, I was able to implement it and pass the coordinates manually, but I need to create the coordinates dynamically coming from the bank in Mongodb, on the positions part, I’m having trouble putting the data coming from the database and the code reading it as coordinates instead of reading it as an array. If I have any number in the array it works but only from one to one, I need it to list all latitudes and longitudes and create all points at once. follows the code with the coordinates entered manually (so it works statically)
import React, { Component } from 'react';
import Map from './mapa';
const data = [
{ lat: -23.532881, lng: -46.792004 },
{ lat: -23.532200, lng: -46.781681 },
{ lat: -23.532681, lng: -46.782104 },
{ lat: -23.532281, lng: -46.792084 },
{ lat: -23.532881, lng: -46.792005 }
];
export default class IndexMapa extends Component {
render() {
return ( <React.Fragment>
<Map center={{ lat: -23.532881, lng: -46.792004 }} zoom={14} positions={data} />
</React.Fragment>);
}
}
I need this constant date to be dynamic with the points I have on Mongodb. follows the code I have but is returning only 1 coordinate (only 1 point on the map). Obs. if I do not set a number in lat and lng, the code returns an array and no point appears on the map.
import React, { Component } from 'react';
import Map from './mapa';
import api from '../../../services/api';
// const data = [];
export default class IndexMapa extends Component {
constructor(props) {
super(props);
this.state = {
position:[]
}
}
async componentDidMount() {
await api.get('/api/clientes.coordenada').then(res => {
const local = res.data;
let lng = [];
let lat = [];
local.forEach(element => {
lat.push(element.lat);
lng.push(element.lon);
});
// console.log(local);
this.setState({
position: [
{lat: lat[0], lng: lng[0]}
]
});
});
// console.log(this.state.position);
}
render() {
return (
<React.Fragment>
<Map center={{ lat: -23.532881, lng: -46.792004 }} zoom={14} positions={this.state.position} />
</React.Fragment>);
}
}
thank you in advance.
how they are returned at this address:
/api/clientes.coordenada
?– novic
There are errors in your code
await/async
and in the same codethen
either one or the other.– novic
this address returns these variables id, lat and Lon, like this: { "_id": "5fb9ef8193f4ac34cc242187", "lat": "-46.781061", "Lon": "-23.531740" },(returns varias this is just 1 example of them)
– Rmmh
I’ll fix the await/async, I’m new with React and so it was working so I didn’t know it was wrong ,but the biggest problem is to get by this data that comes from Mongo instead of the statical data
– Rmmh
return a
array
of that? like[{},{},{}]
?– novic
Right inside each key goes the 3 variables the way I posted
– Rmmh
Do you have any tips that might help?
– Rmmh