1👍
✅
Problem
You are creating new map instance each time directions()
is called.
mapOptions = {
zoom: 7,
center: { lat: -28.4792625, lng: 24.6727135 },
mapTypeId: "terrain"
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions); //--> here
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
... // rest of the code
Solution
save the map
instance in one of the data
variables in component and use the same in directions()
method.
data() {
return {
mapOptions: {},
map: null // --> HERE
};
},
methods: {
initMap() {
//This function initialises the page with a new google map element
mapOptions = {
zoom: 7,
center: { lat: -28.4792625, lng: 24.6727135 },
mapTypeId: "terrain"
};
this.map = new google.maps.Map(document.getElementById("map"), mapOptions); // --> HERE
},
directions() {
//This directions method is executed once a button is pressed on the UI
//How do I get this directions method to update the map already created in
//initMap() instead of creating a second map and generating a second call
//to the Google Maps API?
mapOptions = {
zoom: 7,
center: { lat: -28.4792625, lng: 24.6727135 },
mapTypeId: "terrain"
};
//var map = new google.maps.Map(document.getElementById("map"), mapOptions); //--> HERE delete this
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsService.route(
{
origin: "Kimberley, Northern-Cape, South Africa",
destination: "Potchefstroom, South Africa",
travelMode: "DRIVING"
},
function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
//I plan to do some post-processing here
}
else {
window.alert("Directions request failed: " + status);
}
}
);
directionsDisplay.setMap(this.map); // --> HERE
}
👤spc
Source:stackexchange.com