用户提交位置后重新定位Google地图

时间:2016-01-31 05:44:15

标签: javascript api google-maps location center

我正在建立一个旅行计划员,要求用户输入并提交他/她前往的城市的名称。我已经启动了一个地图并将第一个位置设置为SF,但我希望它根据用户输入的位置重新定位。

这两个引用(除了谷歌地图API文档)我在发布之前遵循 - 没有为我工作(我显然缺少一些东西)。我得到了map.setCenter()不是函数。

optional unwrapping

Google Maps SetCenter function refusing to work

          <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);
}

1 个答案:

答案 0 :(得分:2)

我刚想通了!

我在initMap函数之外定义了变量map,然后删除了&#34; var&#34;在initMap函数内部的map前面,所以它更新了全局map变量,而不是仅将它存储在initMap中。那就做到了!