如何使用google api的placekicker的place_changed事件?

时间:2017-05-24 09:38:10

标签: javascript jquery google-places-api gmsplacepicker

我差不多完成但是我遇到一个问题就是我的问题: -

I have successfully implement the placekicker with uk country only. Here is my code:-
Input location here:<input id="searchTextField" type="text" size="50">
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script>
var pac_input = document.getElementById('searchTextField');
$(function() {
  var options = {
    componentRestrictions: {
      country: 'uk' //PUT YOUR COUNTRY CODE HERE!!
    }
  };
  var autocomplete = new google.maps.places.Autocomplete(pac_input, options);
});

当我运行上面的代码时,它只会显示我的结果,但是当我在上面的代码中添加更多功能时,它会显示整个国家的记录。添加的代码在这里: -

<script type="text/javascript">
    google.maps.event.addDomListener(window, 'load', function () {
        var places = new google.maps.places.Autocomplete(document.getElementById('searchTextField'));
        google.maps.event.addListener(places, 'place_changed', function () {
            var place = places.getPlace();
            var address = place.formatted_address;
            var latitude = place.geometry.location.lat();
            var longitude = place.geometry.location.lng();
            var mesg = "Address: " + address;
            mesg += "\nLatitude: " + latitude;
            mesg += "\nLongitude: " + longitude;
            alert(mesg);
        });
    });
</script>

当我添加此代码时,它将给出我从placepicker中选择的每个地方的纬度和经度现在问题是它将提供全国数据,但是当我删除此代码时它给我英国结果。请帮我。我做错了什么。在此先感谢:)

1 个答案:

答案 0 :(得分:0)

尝试在自动填充功能中传递选项

var options = {
    componentRestrictions: {
      country: 'uk' //PUT YOUR COUNTRY CODE HERE!!
    }
  };
    google.maps.event.addDomListener(window, 'load', function () {
        var places = new google.maps.places.Autocomplete(document.getElementById('searchTextField'), options );  //// options added
        google.maps.event.addListener(places, 'place_changed', function () {
            var place = places.getPlace();
            var address = place.formatted_address;
            var latitude = place.geometry.location.lat();
            var longitude = place.geometry.location.lng();
            var mesg = "Address: " + address;
            mesg += "\nLatitude: " + latitude;
            mesg += "\nLongitude: " + longitude;
            alert(mesg);
        });
    });