Currently, I am developing a small website that utilizes the Google Maps API and AJAX to load directions based on selected locations from a dropdown menu. The database stores latitude and longitude coordinates of various locations, which are retrieved via an asynchronous call to the server in JSON format. Every time this call is made, my showPosition function is triggered.
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
console.log(myObj[0].lat);
console.log(this.responseText);
showPosition(myObj);
}
};
The purpose of the showPosition function is to display the map with the corresponding directions.
<script language="JavaScript">
var mapholder = document.getElementById("mapholder");
function showPosition(myObj) {
// Extracting coordinates
console.log(myObj);
fromDirectionLat = myObj[0].lat;
fromDirectionLong = myObj[0].long;
toDirectionLat = myObj[1].lat;
toDirectionLong = myObj[1].long;
// Styling the map container
mapholder.style.height = '600px';
mapholder.style.width = '600px';
mapholder.style.border = 'medium solid #555555';
var myOptions = {
center: latlong,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
var directionService = new google.maps.DirectionsService;
var directionDisplay = new google.maps.DirectionRenderer;
var map = new google.maps.Map(document.getElementById('mapholder'), myOptions);
directionDisplay.setMap(map);
var onChangeHandler = function() {
displayRoute(directionService, directionDisplay);
}
function displayRoute(directionService, directionDisplay) {
var originF = new google.maps.LatLng(fromDirectionLat, fromDirectionLong);
var destinationT = new google.maps.LatLng(toDirectionLat, toDirectionLong);
directionsService.route({
origin: originF,
destination: destinationT,
travelMode: 'DRIVING'
},
function (response, status) {
if(status == 'OK')
directionDisplay.setDirections(response);
else
window.alert("Failed to retrieve directions");
});
}
}
</script>
An error displayed in the console reads:
ReferenceError: latlong is not defined Ajax:93:17
showPosition http://localhost:8888/Ajax/:93
onreadystatechange http://localhost:8888/Ajax/:37
I am currently navigating through learning these functionalities and troubleshooting this issue has proven quite challenging for me as a beginner.