城镇上的谷歌地图条件

时间:2015-08-03 07:12:06

标签: javascript google-maps

我想在我的代码中使用用户输入起点和终点的条件,我想检查起点是否检查它是否位于伦敦,所以我发现这个代码在功能上运行良好但是我希望它的变量town在此函数之外生成函数,因此我创建了检查点。

var input = document.getElementById('start');         
var autocomplete = new google.maps.places.Autocomplete(input);          

autocomplete.bindTo('bounds', map); 
var infowindow = new google.maps.InfoWindow(); 

// when user has clicked on an autocomplete suggestion
google.maps.event.addListener(autocomplete, 'place_changed', function() {
    infowindow.close();
    var place = autocomplete.getPlace();

    // get town of selected place
    function getTown(address_components) {
        var geocoder = new google.maps.Geocoder();  result = address_components;
        var info = [];
        for (var i = 0; i < result.length; ++i) {
            if (result[i].types[0] == "locality") {
                return result[i].long_name;
            }
        }
    };
    var town = getTown(place.address_components);
        // if place is in London, move marker to the place
        if (town == 'London') {
          alert('in London');
    } else {
        // if not, do nothing and alert user
        alert('you must click on a place in London');
    }
});  

如何在整个页面上访问此函数之外的var town,以便我根据它创建条件?

1 个答案:

答案 0 :(得分:1)

您可以在回调范围之外创建一个变量,将结果设置为。

&#13;
&#13;
var input = document.getElementById('start');         

var map = new google.maps.Map(document.getElementById('map-canvas'), {
  zoom: 12,
  center: {lat: 51.507351, lng: -0.127758}
});

var autocomplete =  new google.maps.places.Autocomplete(input);     
autocomplete.bindTo('bounds', map); 

var town;
// when user has clicked on an autocomplete suggestion
google.maps.event.addListener(autocomplete, 'place_changed', function() {
  function getTown(address_components) {
    result = address_components;
    var info = [];
    for (var i = 0; i < result.length; ++i) {
      if (result[i].types[0] == "locality") {
        return result[i].long_name;
      }
    }
  };
  document.getElementById('place').innerHTML = '';
  document.getElementById('town').innerHTML = '';
  town = getTown(autocomplete.getPlace().address_components);
});

function inLondonCheck(placeName) {
  document.getElementById('place').innerHTML = placeName + " in London? " + (town === 'London');
  document.getElementById('town').innerHTML = town || '';
}

setInterval(function() {
  if (town) inLondonCheck(autocomplete.getPlace().name);
}, 500);
&#13;
html,
body,
#map-canvas {
  height: 100%;
  margin: 0;
  padding: 0;
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>

<input id="start">
<div>Place<pre id="place"></pre></div>
<div>Town<pre id="town"></pre></div>
<div id="map-canvas"></div>
&#13;
&#13;
&#13;