I'm using Google Maps Javacript API to draw a polyline. I intended to create a function to remove the polyline when a button is clicked. The HTML code for the button is the following:
<button type="button" class="btn btn-danger" id="clear_button" onclick="removeLine()">Borrar ruta</button>
and the Javascript code for the drawing the polyline and removing it is the next:
var map;
var flightPath;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: {lat: 37.176709, lng: -3.599057},
mapTypeId: 'terrain'
});
google.maps.event.addDomListener(document.getElementById('route_button'), 'click', function() {
var date_data = document.getElementById('datepicker').value;
console.log(date_data);
$.ajax({
url:"data_fetcher.php",
type:"POST",
data: {date_value:date_data},
dataType: 'json',
success: function(respond){
var flightPlanCoordinates = respond;
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
console.log("AJAX level request was successful");
},
error: function(){
console.log("AJAX level request was a failure");
}
});
});
}
// Eliminar polilinea
function removeLine() {
flightPath.setMap(null);
}
everything works fine, but when I click the button to remove the polyline, the console throws the following error:
Uncaught TypeError: Cannot read property 'setMap' of undefined at removeLine (device.php:101) at HTMLButtonElement.onclick (device.php:196)
even though I declared flightPath var in the global scope. Every help will be appreciated.
In the success function, you're declaring a local variable with the same name, JS will use the closest variable it finds when assigning variables. To fix this simply remove the var
.
success: function (respond) {
var flightPlanCoordinates = respond;
flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
console.log("AJAX level request was successful");
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.