位置搜索自动完成并选择城市和州

时间:2018-01-30 08:16:57

标签: javascript google-maps google-maps-api-3 autocomplete

       <script>
            function initMap() {

                var input = document.getElementById('searchInput');
                var autocomplete = new google.maps.places.Autocomplete(input);
                var infowindow = new google.maps.InfoWindow();
                autocomplete.addListener('place_changed', function () {
                    infowindow.close();
                    var place = autocomplete.getPlace();
                    if (!place.geometry) {
                        window.alert("Autocomplete's returned place contains no geometry");
                        return;
                    }
                    //Location details
                    for (var i = 0; i < place.address_components.length; i++) {
                        if (place.address_components[i].types[0] === 'postal_code') {
                            document.getElementById('postal_code').value = place.address_components[i].long_name;
                        }
                        if (place.address_components[i].types[0] === 'country') {
                            document.getElementById('country').value = place.address_components[i].long_name;
                        }
                        if (place.address_components[i].types[0] === 'cities') {
                            document.getElementById('cities').value = place.address_components[i].long_name;
                        }
                    }

                    document.getElementById('location').value = place.formatted_address;
                    document.getElementById('lat').value = place.geometry.location.lat();
                    document.getElementById('lon').value = place.geometry.location.lng();
                });
            }
            google.maps.event.addDomListener(window, 'load', initialize);
        </script>

我检索国名,我检索pincode
我也可以检索位置纬度和经度
但是我无法检索城市
Pleae检查此代码并告诉我什么错误在我的代码中,我也在反击区和州

1 个答案:

答案 0 :(得分:0)

为地方改变城市:

if (place.address_components[i].types[2] === 'locality')