Utilizing AJAX to integrate the Google Maps Direction API

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.

Answer №1

You are utilizing a variable that has not been previously defined

center: latlong

The variable latlong is not declared anywhere else in your code. To fix this, you should define it as the center of the map you wish to display

var latlong = new google.maps.LatLng(your_center_lat, your_center_long)

or

center: new google.maps.LatLng(your_center_lat, your_center_long)

The responsibility of defining the center lies with you :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for handling HTTP responses prior to initializing a data-table in AngularJS

Here is a snippet of code showcasing a process involving multiple http requests and the use of promises: The first step involves calling a service to initiate an http request. Upon receiving the response, a map is created based on the data, which will be ...

Is it necessary for a TypeScript Library's repository to include the JavaScript version?

Is it necessary to include a JavaScript version of the library along with the Typescript repository for consumers? Or is it best to let consumers handle the compilation process themselves? Or should I consider another approach altogether? ...

Wordpress tabs with dynamic content

I came across a code on webdeveloper.com by Mitya that had loading content tabs and needed the page to refresh after clicking the tab button. It worked perfectly fine outside of WordPress, but when I tried implementing it into my custom theme file, it didn ...

The lack of intellisense in VS Code for Node.js poses a significant challenge for developers

I am facing a problem with IntelliSense in Visual Studio Code. Despite installing multiple extensions, it is not working as expected. The IntelliSense feature only shows functions and variables that have already been used in my code file. Below is the li ...

When the user initiates a fetch request, they will be directed to the POST page as a standard

Whenever I utilize fetch for a post request, I encounter an issue where the user is not redirected to the Post page as they would be with a regular form submission. My goal is to be able to direct the user to a specific location on the server side at app ...

NodeJS error: Attempted to set headers after they have already been sent to the client

As a beginner, I have encountered an error message stating that the API is trying to set the response more than once. I am aware of the asynchronous nature of Node.js but I am struggling to debug this issue. Any assistance would be greatly appreciated. rou ...

Incorporating Angular to dynamically fetch data through AJAX and fill in content post-page render

As a backend API developer diving into AngularJS (version 1) for the first time with my current project, I have encountered a scenario that requires me to fetch server-side content dynamically post-render. The page is set up with ng-app="app" in the <ht ...

How can I dynamically redirect based on the selected radio button value in a React application?

I've been attempting to use the "navigate" method from "react-router-dom" to redirect users from the Login screen based on the radio button they click. I've tried using states, but I'm unsure if that's the best approach or if there&apos ...

Dynamically manipulate the perspective camera by moving and rotating it using a 4x4 matrix

Greetings, esteemed community members, For the past few days, I have been struggling with an issue related to updating the View Matrix (4x4) of my camera. This update is crucial for positioning objects within an AR-Scene created using three.js. The custo ...

Displaying information in form using ajax within the laravel framework

I am currently utilizing ajax to retrieve data from a database. While I am able to successfully retrieve the data on the backend, I am facing difficulties displaying it in the input field below. I have tried writing some code, but it seems that the JavaScr ...

Automatically populate form fields with data from the clicked row in the HTML table when using JSP

Attempting to populate form fields using jQuery or JavaScript with row elements selected by clicking on the row. Tried a solution from Stack Overflow that didn't work as expected. I'm new to this, so please bear with me. (http://jsbin.com/rotuni/ ...

Refresh Google Maps without showing gray areas on the screen

Currently, I am utilizing the Google Maps API v3 in javascript and frequently reloading the map using an app.get while also incorporating layers and bookmarks via mongodb. Whenever I reload the map to erase everything, a gray background appears in the div ...

Pug conditional elements not styling with CSS

Currently immersed in the world of Pug, node.js, and express as I build a web application. Facing hurdles when trying to style elements within Pug conditionals using CSS. For instance, consider this Pug snippet: div(id='outside') if authoris ...

Can AJAX Delete requests be executed without using jQuery?

Is it possible to use AJAX delete request without using jQuery? My JSON object at localhost:8000 appears like this: { "Students":[{"Name":"Kaushal","Roll_No":30,"Percentage":94.5}, {"Name":"Rohit","Roll_No":31,"Percentage":93.5}, {"Name":"Kumar ...

Problem with the property `className` not adding correctly on `$scope.eventSource`

Currently, I am utilizing the AngularJS directive to integrate the Arshaw FullCalendar. However, I am encountering an issue where the className specified in $scope.eventSource is not appearing on the event object. Here is a snippet of my code: $scope.even ...

Ensure that Angular resolver holds off until all images are loaded

Is there a way to make the resolver wait for images from the API before displaying the page in Angular? Currently, it displays the page first and then attempts to retrieve the post images. @Injectable() export class DataResolverService implements Resolv ...

What is the solution to the error "modal is not defined" in Vue.js?

Hey guys, I need some help with an error that popped up: [Vue warn]: Error in v-on handler: "TypeError: $(...).modal is not a function". The issue is with the modal function Below is the code snippet from my welcome.blade.php: <body> &l ...

According to Intelijj IDEA, the success function in the AJAX request is reported as unused

I've encountered an issue and I'm unsure of the cause. This is my code for testing AJAX requests: function sendAJAX() { var dataToSend = {}; dataToSend["username"] = $("#username").val(); dataToSend["age"] = $("#age").val(); data ...

Utilize vue.js to cache and stream videos

I'm new to the world of vue.js and I'm facing a certain dilemma. I implemented a caching system using resource-loader that preloads my images and videos and stores the data in an array. Everything is functioning correctly, but now I'm unsur ...

What steps should be followed to incorporate a user image and name when a user submits a comment in a functional JavaScript comments section?

After stumbling upon a comment box submitted by the user Rick Hitchcock (link here), I realized that I need to incorporate a generic user image and a username (could be anonymous) when a user submits a comment. Unfortunately, I am clueless on how to achiev ...