Search code examples
javascriptapigoogle-mapslocationcenter

Re-center Google Map after user submits location


I'm building out a travel planner that asks a user to enter and submit the name of the city s/he's traveling to. I've initiated a map and set the first location to SF, but I want it to re-center based on the location the user entered.

These are two references (besides the Google Maps API documentation) I followed before posting - neither worked for me (I'm obviously missing something). I'm getting that map.setCenter() isn't a function.

Google Maps SetCenter function refusing to work

Google Maps API v3: How to Set Zoom Level And Map Center To User Submitted Location?

          <h3>I'm traveling to: </h3>
          <input class="inputBox" type="text" name="destination" id="destination" placeholder="e.g., Barcelona, Spain or China" maxlength="35">
          <input type="submit" class="form" id="form">


  <script type="text/javascript">

  function initMap() {
  var myLatlng = {lat: 37.7751, lng: -122.4194};

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: myLatlng
  });
}

var button = document.querySelector("input.form");
    var userSelectLat;
    var userSelectLng;

    //add an event listener which executes the callback function, geoLocation, when the Submit button is clicked
    button.addEventListener("click", getLocation);

    function getLocation(event) {
      event.preventDefault()
      //store city entered into a variable, put it in quotes, and add that to the geocode URL
      var city = document.querySelector("input#destination.inputBox").value;
      var cityInQuotes = "\"" + city + "\""
      var geocodeURL = "https://maps.googleapis.com/maps/api/geocode/json?address="+cityInQuotes+"AIzaSyBMEriLb8zqxFSVBWArM6n3MxonN5d-cLY";
      //return JSON and
      $.get(geocodeURL,printCoordinates)
  }

  function printCoordinates(results) {
    if (results.status === "ZERO_RESULTS") {
      alert("Location not found. Try searching for a city or more specific location.")
  } else {
    userSelectLat = results.results[0].geometry.location.lat;
    userSelectLng = results.results[0].geometry.location.lng;
    console.log('arrayresults = '+userSelectLat,userSelectLng);
    }
    //re-center map based on new location
    var relocate = new google.maps.LatLng(userSelectLat, userSelectLng);
    alert("setting the center to: " + relocate);
    map.setCenter(relocate);
}

Solution

  • I just figured it out!

    I defined the variable map outside of the initMap function, then deleted out the "var" in front of map inside the initMap function so it was updating the global map variable instead of storing it inside the initMap only. That did it!