Search code examples
javascriptgoogle-mapsgoogle-maps-api-3google-geocoder

Google Maps: getting directions after converting address to coordinates through geocoder


I got the Google Maps to work with Local Context thanks to an answer from @eocodezip but having trouble enabling directions from the nearby locations that popped up.

Here's the code I'm using. It seems like "directionsOptions: { origin: center }" runs too late, but I can't move it up since 'center' isn't defined until later. Is there any way to setCenter earlier? At least I think that's the issue.

let map;

function initMap() {
  const localContextMapView = new google.maps.localContext.LocalContextMapView({
    element: document.getElementById("map"),
    placeTypePreferences: ["restaurant", "tourist_attraction",
"bar", "cafe", "book_store", "convenience_store", "hospital"],
    maxPlaceCount: 24,
  });
  
  map = localContextMapView.map;
  let geocoder = new google.maps.Geocoder();
  geocoder.geocode({ address: "25325 Main St, Newhall, CA, USA" }, (results, status) => {
    if (status === "OK") {
      const center = results[0].geometry.location;
      map.setCenter(center);
  new google.maps.Marker({ position: center, map: map});
  map.setOptions({
    directionsOptions: { origin: center },
    center: center,
    zoom: 14,
  });
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}
#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>Local Context Basic</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=localContext&v=beta" defer></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map"></div>
</body>

</html> 


Solution

  • google.maps.Map doesn't have a DirectionsOptions property. Please refer to the docs. You need to set it on localContextMapView:

    localContextMapView.directionsOptions = {
      origin: center
    };
    

    That said, with the code you provided, if the geocoder fails, you will have no map showing at all. Is that the intended behavior?

    let map;
    
    function initMap() {
      const localContextMapView = new google.maps.localContext.LocalContextMapView({
        element: document.getElementById("map"),
        placeTypePreferences: ["restaurant", "tourist_attraction",
          "bar", "cafe", "book_store", "convenience_store", "hospital"
        ],
        maxPlaceCount: 24,
      });
    
      map = localContextMapView.map;
      let geocoder = new google.maps.Geocoder();
      
      geocoder.geocode({
        address: "25325 Main St, Newhall, CA, USA"
      }, (results, status) => {
        if (status === "OK") {
        
          const center = results[0].geometry.location;
          
          map.setOptions({
            center: center,
            zoom: 14
          });
          
          new google.maps.Marker({
            position: center,
            map: map
          });
    
          localContextMapView.directionsOptions = {
            origin: center
          };
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
    #map {
      height: 400px;
    }
    
    
    /* Optional: Makes the sample page fill the window. */
    
    html,
    body {
      height: 400px;
      margin: 0;
      padding: 0;
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <title>Local Context Basic</title>
      <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
      <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=localContext&v=beta" defer></script>
      <!-- jsFiddle will insert css and js -->
    </head>
    
    <body>
      <div id="map"></div>
    </body>
    
    </html>

    If instead you set a default center and zoom, and adjust it when the geocoder is successful (along with setting new locationRestriction on the local context map), you would always have a map showing.

    let map;
    
    function initMap() {
      const localContextMapView = new google.maps.localContext.LocalContextMapView({
        element: document.getElementById("map"),
        placeTypePreferences: ["restaurant", "tourist_attraction",
          "bar", "cafe", "book_store", "convenience_store", "hospital"
        ],
        maxPlaceCount: 24,
      });
    
      map = localContextMapView.map;
      
      // Update localContext when user drags the map
      map.addListener('dragend', function() {
        localContextMapView.locationRestriction = map.getBounds();
      });
      
      // Set default center & zoom somewhere over NY
      map.setOptions({
        center: new google.maps.LatLng(40.61,-73.97),
        zoom: 10
      });
      
      let geocoder = new google.maps.Geocoder();
      
      geocoder.geocode({
        address: "25325 Main St, Newhall, CA, USA"
      }, (results, status) => {
        if (status === "OK") {
        
          const center = results[0].geometry.location;
          
          // Set new center and zoom
          map.setOptions({
            center: center,
            zoom: 14
          });
          
          // Set the location restriction to the new map bounds
          localContextMapView.locationRestriction = map.getBounds();
          
          new google.maps.Marker({
            position: center,
            map: map
          });
    
          localContextMapView.directionsOptions = {
            origin: center
          };
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
    #map {
      height: 400px;
    }
    
    
    /* Optional: Makes the sample page fill the window. */
    
    html,
    body {
      height: 400px;
      margin: 0;
      padding: 0;
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <title>Local Context Basic</title>
      <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
      <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=localContext&v=beta" defer></script>
      <!-- jsFiddle will insert css and js -->
    </head>
    
    <body>
      <div id="map"></div>
    </body>
    
    </html>