0

I am using the example from this document as reference. https://developers.google.com/maps/documentation/javascript/examples/layer-traffic

Basically, I have a html file and an external js file.

<!DOCTYPE html>

<html>
  <head>
    <title>Transit Layer</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
    <div id="map"></div>

  
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap(51.501904,-0.115871)&v=weekly"
      
    ></script>
  </body>
</html>

External js script:

function initMap(lat, lon) {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 13,
    center: { lat: lat, lng: lon },
  });
  const transitLayer = new google.maps.TransitLayer();

  transitLayer.setMap(map);
}

window.initMap = initMap;

How do I pass arguments initMap(51.501904,-0.115871) to the js function from html? I tried this in jsfiddle and it didn't work.

6
  • 1
    What arguments do you want to pass? Commented Aug 12, 2022 at 1:30
  • @Barmar lat and long. Commented Aug 12, 2022 at 1:33
  • It's based on the map - user defined. Commented Aug 12, 2022 at 1:34
  • <button type="button" onclick="initMap(51.501904,-0.115871)">Click to initialize map</button> Commented Aug 12, 2022 at 1:35
  • 1
    You cannot do that the way your code indicates you intend. You only can pass arguments to a function using HTML if you call that function passing the argument in an HTML event attribute. The script tag results in a request to the informed URL. The response coming from this URL is included in the page as a script. You would only be able to pass arguments through the URL if the server receiving that request uses this to create a dynamic script with the arguments you passed, which is not the case. But why not define the lat and lng direct in the script? Or define them in a variable and use? Commented Aug 12, 2022 at 1:37

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.