-2

I'm not sure why I keep getting an undefined error when I use a variable defined in an external javascript filE. i want to access the addresses variable from vvvjavascript.js file in my html file. I get the error - Uncaught ReferenceError: addresses is not defined". Not sure what's causing that. Codes are below

External Javascript file (vvvjavascript.js)`

    var addresses = [
  [
    [43.674687, -79.430955],
    [43.668560, -79.394924]
  ],
  [
    [43.682191, -79.417886],
    [43.680790, -79.417379]
  ],
  [
    [43.640381, -79.394508],
    [43.640575, -79.394586]
  ]
];

Second File

  function initMap() {
    var directionsRenderer = new google.maps.DirectionsRenderer();
    var directionsService = new google.maps.DirectionsService();
    var map = new google.maps.Map(document.getElementById("map"), {
      zoom: 7,
      center: {
        lat: 41.85,
        lng: -87.65
      }
    });
    directionsRenderer.setMap(map);
    directionsRenderer.setPanel(document.getElementById("right-panel"));
    

    var onChangeHandler = function() {
      calculateAndDisplayRoute(directionsService, directionsRenderer);
    };

    document.getElementById("submit").addEventListener("click", onChangeHandler);
  }
  
// calcRoute();


  function calculateAndDisplayRoute(directionsService, directionsRenderer) {
    var start_lat = document.getElementById("origin_lat").value;
    var start_lng = document.getElementById("origin_long").value;

    var end_lat = document.getElementById("destination_lat").value;
    var end_lng = document.getElementById("destination_long").value;

    var start = new google.maps.LatLng(start_lat, start_lng); 
    var end = new google.maps.LatLng(end_lat, end_lng); 

    directionsService.route(
      {
        origin: start,
        destination: end,
        travelMode: "DRIVING"
      },
      function(response, status) {
        if (status === "OK") {
          directionsRenderer.setDirections(response);
          
          var foundPoints = [];
      for (k = 0; k < addresses.length; k++) {
        if (google.maps.geometry.poly.isLocationOnEdge(addresses[k][0], response.routes[0], 1e-3) || google.maps.geometry.poly.isLocationOnEdge(addresses[k][1], response.routes[0], 1e-3)) {
            foundPoints.push(k);
          alert("route number " + k );
        } 
      }
          
        } else {
          window.alert("Directions request failed due to " + status);
        }
 
      }
       
    );
  }

 

HTML for Second File

<!DOCTYPE html>
<html>
  <head>
    <title>Displaying Text Directions With setPanel()</title>
    <script type="text/javascript" src="vvvjavascript.js"></script>

    <script
      src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" defer></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
  
    <div id="right-panel"></div>
    <div id="map"></div>
  
<button type="button" id="submit">Submit</button>
  <label for="origin_lat">Origin latitude:</label>
  <input type="text" id="origin_lat" name="origin_lat" value=" "><br>
   <label for="origin_long">Origin longitude:</label>
  <input type="text" id="origin_long" name="origin_long" value=" "><br>
  <label for="destination_lat">Destination latitude:</label>
  <input type="text" id="destination_lat" name="destination_lat" value=" "><br>
  <label for="destination_long">Destination longitude:</label>
  <input type="text" id="destination_long" name="destination_long" value=" "><br><br><br><br>


  
  </body>
</html>
  • 3
    How are you loading the "second file"? Please provide a [mcve] that demonstrates your issue. including any required HTML/CSS (the map doesn't display if I include the "second file" in the HTML as the map doesn't have a size). I would also be useful to have test data (values for the origin/destination coordinates that are reasonable) The error I get with the posted code is `Uncaught TypeError: a.lng is not a function` (it can find the `addresses` variable, but those aren't `google.maps.LatLng` objects) – geocodezip Aug 07 '20 at 00:32
  • 1
    [isLocationOnEdge](https://developers.google.com/maps/documentation/javascript/reference/geometry#poly.isLocationOnEdge) requires the first argument to be a `google.maps.LatLng` – geocodezip Aug 07 '20 at 00:34
  • Here's a link to the [jsfiddle](https://jsfiddle.net/ntmrhb75/1/) with CSS included. I don't think it's able to find the addresses variable because I still can't create an alert statement to output that variable. – mavrick1717 Aug 07 '20 at 23:08
  • It ca't load the script because it is on your local `C:` drive and the jsfiddle isn't allowed to access that (it isn't allowed to access my local `C:` drive either, but this linux box doesn't have a `C:` drive). – geocodezip Aug 07 '20 at 23:14
  • @geocodezip running the html file locally still doesn't solve the problem. Still keep getting addresses undefined error – mavrick1717 Aug 08 '20 at 22:19
  • Try https://codesandbox.io/ for multiple files. – TimTIM Wong Aug 15 '20 at 06:43

2 Answers2

0

Where do you include your second file? My first guess is, that your code from second file is executed before the vvvjavascript.js is loaded. Thats why it cant know the variable. Here are some good examples, how to include How do I include a JavaScript file in another JavaScript file?

jgrp
  • 32
  • 4
  • I'm using jsfiddle to work on this. Not sure why the second file runs before the first file. I don't think there is anything wrong with the way I referenced the first file in the tag of the second file – mavrick1717 Aug 07 '20 at 22:51
0

You need to import the first javascript file into the second one. If you have access to the first one the easiest way is to export the variable from there: export var addresses = [... and import into the second one: import { addresses } from './vvvjavascript.js'.

Jacob P
  • 148
  • 5
  • tried this too. Got these errors Uncaught SyntaxError: Unexpected token 'export' Uncaught SyntaxError: Cannot use import statement outside a module – mavrick1717 Aug 08 '20 at 22:21