1👍
✅
If id
is not required for the marker to show on the map, try this:
Add the marker with empty id
before GET/POST calls. This way there shouldn’t be any delays.
And update the id
value once your POST calls finishes.
Check the comments in the code
createMarker(event){
var lat = event.latLng.lat();
var lng = event.latLng.lng();
const latLng = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&key='
// add the marker to the map first
this.markers.push({ 'id': '',
'lat': lat,
'lng': lng})
// save the position of the marker, so we can add `id` later
var index = this.markers.length - 1;
axios.get(latLng)
.then(response => {
const name = response.data.results[0].address_components[5].long_name + ', '
+ response.data.results[0].address_components[3].long_name
console.log(response)
axios.post('/marker', {
userId: this.$store.state.auth.userId,
marker: event.latLng,
name: name
}).then(response => {
// update marker index
this.markers[index].id = response
}).catch((error) => console.log(error));
}).catch((error) => console.log(error))
2👍
Yes, you are right. The final result is the delay of two network requests. However, you are not correctly utilizing the promise chain. It resembles the callback hell. You can write it in a more elegant fashion like:
createMarker(event) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
const latLng = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&key=';
const userId = this.$store.state.auth.userId;
axios.get(latLng)
.then((response) => response.data.results[0])
.then((x) => `${x.address_components[5].long_name},${x.address_components[3].long_name}`)
.then((name) => axios.post('/marker', {
name, userId
marker: event.latLng,
}))
.then((response) => this.markers.push({
id: response.data.marker.id,
lat: response.data.marker.lat,
lng: response.data.marker.lng
}))
.catch((error) => console.log(error));
}
Promises help you flatten nested asynchronous calls.
Source:stackexchange.com