Embedding Variables into Google Maps Script Tag

I'm looking to integrate a Google Maps direction feature onto my page. Currently, the JS element is hardcoded with the origin set as Miami, FL, destination as Buffalo, NY, and waypoints also static. However, I want to make these values dynamic by retrieving location strings from a JSON file on the backend using Angular's http.get.

How can I adjust the script to allow for dynamic origins, destinations, and waypoints?

<script>
  function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 41.85, lng: -87.65},
    scrollwheel: false,
    zoom: 7
  });

  var directionsDisplay = new google.maps.DirectionsRenderer({
    map: map
  });

  // Set destination, origin and travel mode.
  var request = {
    destination: "Miami, FL",
    origin: "Buffalo, NY",
    travelMode: google.maps.TravelMode.DRIVING,
    waypoints: [
    {
      location:"Richmond, VA",
      stopover:true
    },{
      location:"Washington, DC",
      stopover:true
    }],
};

var directionsService = new google.maps.DirectionsService();

directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay.setDirections(response);
  }
 });
}
</script>

Answer №1

Below is a sample JSON array provided for reference. In this scenario, the array is defined within the JavaScript scope, but ideally, you would access it using ajax. Regardless of the method chosen, ensure that the code is organized accordingly.

Array initialization:

var placesJSON = 
  [   
 {
     "location":"Richmond, VA",
      stopover:true

 },
  {
      "location":"Washington, DC",
      "stopover":true

  },
  {
      "location":"Atlanta",
      "stopover":true

  }
  ];

Dynamic variables:

var request = {
    destination: "Miami, FL",
    origin: "Buffalo, NY",
    travelMode: google.maps.TravelMode.DRIVING,
    waypoints: [
    {
      location:placesJSON[0].location,
      stopover:placesJSON[0].stopover
    },{
      location:placesJSON[2].location,
      stopover:placesJSON[2].stopover
    }],
};

To see a live demonstration, visit this fiddle link: https://jsfiddle.net/eugensunic/45n45cpd/1/

If you prefer to access your JSON array by a specific key instead of an index, consider iterating through the array and using conditional statements like the one below:

if(desired_destination== placesJSON[index].location){// select this place} 

This approach will help validate your request before proceeding further.

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

The Axios response interceptor consistently yields an Undefined value

The site's API caller, utilizing an Axios instance, employs the function processResponse to handle the response data before sending it to the frontend for display. However, an issue arises when attempting to retrieve the response data in the frontend ...

Convert the values in the array from strings to numbers

My array contains the following values: var items = [Thursday,100,100,100,100,100,100] I am retrieving these values from the URL query string which is why they are all in string format. I am looking for a way to make all columns except the first one as ...

Ways to update a prop and reset it to its original state using React Hooks

My goal is to take a string prop text, trim it, and then pass it to the state of a component. I used to achieve this using the componentDidMount function in the past. However, now I am trying to use the useEffect() hook but encountering an error: "Cannot ...

Dragging left and right using jQuery

Recently, I created a customized carousel featuring images with previous/next arrows for navigation. I am curious if jQuery offers an event that allows users to click on the photo, drag it left or right, and trigger the same action as the arrows currently ...

Using JQuery for sending POST requests in JavaScript

I am currently facing an issue while trying to post JSON data to a server. I have managed to do it successfully using a certain method, which is as follows: <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js">< ...

Encountered an error while trying to install generator-X globally on Windows using npm

Encountering the same error for both of these commands. npm install -g generator-angular-fullstack. npm install -g generator-meanjs. I've tried everything, including searching on Google and Stack Overflow, but I've been stuck on this issue for ...

I need to use JavaScript to create HTML to PDF and then upload the PDF file to a SharePoint Document Library

Our current project requires us to convert HTML to PDF and save it in a SharePoint Document Library. While we have successfully converted the HTML to PDF using Kendo plugin, we are facing challenges with storing it in SharePoint. It's worth noting th ...

Troubleshooting: Inability to Alter CSS of Single Element with jQuery

I am trying to change the grayscale of specific elements when hovering over them individually, instead of changing all elements with the same class at once. I have written the following code for this purpose: tpj(".cftoverlay").hover(function(){ tpj(t ...

Improving the way text entered in an input box is displayed using HTML table cells

Seeking advice on how to display the last two input boxes in a dynamic HTML table so that users can easily view the data they have entered. The issue arises when the length of the data in these columns is large, making it difficult for users to see all the ...

Issue with Slick Grid not updating after Ajax request

I need to update the data on a slick grid when a checkbox is clicked, using an ajax call to retrieve new data. However, I am facing issues where the slick grid does not refresh and the checkbox loses its state upon page load. Jsp: <c:if test="${info ...

What causes the preview pane in an embedded Stackblitz project to not show up?

I've been attempting to integrate Stackblitz projects into my Angular application. The project editor pane displays correctly, but the preview pane is not showing the preview. Instead, it's showing an error message that reads: Error occurred: Err ...

Strangely glitchy navigation bar using jQuery

Over at this website, there's a top navbar that shrinks using jQuery when scrollTop exceeds 100px. The functionality works as intended, but there's an annoying stutter issue where the navbar starts jumping up and down erratically after slight scr ...

What is the best way to access a variable from a class in ES6?

Hey there, I'm having trouble accessing the variable from the KeyCodeClass. Let me walk you through what I've tried so far: Attempt 1 class KeyCodeClass1 { constructor() { this.space; } KeyDown(e) { if (e.keyCode == 3 ...

"Improving React's state array with real-time data from the Spotify API

We have been working on an interesting task involving populating an array with songs using the Spotify API. Since the API allows fetching 50 songs at a time, we devised a loop implementing an offset to acquire a total of 250 songs. Our aim is to update t ...

Mobile-friendly FlexImages grid with justified image sizes

Currently utilizing the FlexImages jQuery plugin for a Justified grid, which is performing well. The only issue I am encountering is the desire for the images to span 100% width on mobile devices (viewport of 550px or less). If interested in checking out ...

Try rotating a triangle in 3D using either CSS or JavaScript

I want to create a right-angle triangle that looks like this . . . . . . . . . . . . . . . . . . but I also want to add a 3D animation that will transform it into a right angle like this . . . . . ...

Attempting to grasp the concept of memory leakage in a more thorough manner

As I dive into the world of frontend development and start learning Vue.js, I came across a paragraph in the tutorial that caught my attention: Vue.js makes rendering a template seem simple, but under the hood it does a lot of work. The data and DOM are ...

Diminishing sheets in the realm of C# web application development

I have been researching ways to incorporate a fading page function, but I am encountering some issues. I am unsure about the specific code that needs to be included in jquery.js and how to integrate this script into all of my web forms or alternatively int ...

"Exploring the world of Typescript's return statements and the

I'm currently grappling with a design dilemma in typescript. Within my controller, I perform a validation process that can either return a 422 response, which ends the thread, or a validated data object that needs to be utilized further. Here's a ...

React components that are rendered after a delay

In my React component, I have multiple child components that I would like to render individually with a delay between each one. Is there a way to accomplish this? Whether the delay is uniform for all children or different for each one, I am open to sugge ...