繁体   English   中英

Google Maps Places API-如何在多个结果上使用Google Maps搜索框获取国家/地区,邮政编码,数字,网站URL

[英]Google Maps places API - How to get Country, Postal-code, Number, Website URL with Google map search box on multiple results

我正在使用带有Google Maps places API的google map搜索框来获取多个结果,例如商店和地方等。

一切正常,我正在获取地址和纬度-经度,但是如何获取其他详细信息(如国家/地区,邮政编码,网站URL,联系电话和等级)。

这是我的代码,任何帮助或建议将不胜感激。

    <!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=My_API_Key&libraries=places&callback=initAutocomplete" async defer"></script>

        <style>
        #wrapper {width:1280px; margin:0 auto;}
            #map {
                width: 100%;
                height:300px;
            }
            .controls {
                margin-top: 10px;
                border: 1px solid transparent;
                border-radius: 2px 0 0 2px;
                box-sizing: border-box;
                -moz-box-sizing: border-box;
                height: 32px;
                outline: none;
                box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
            }
            #searchInput {
                background-color: #fff;
                font-family: Roboto;
                font-size: 15px;
                font-weight: 300;
                margin-left: 12px;
                padding: 0 11px 0 13px;
                text-overflow: ellipsis;
                width: 50%;
            }
            #searchInput:focus {
                border-color: #4d90fe;
            }
            ul {margin:30px 100px;}
            li {margin:5px 0;}
            li span {font-weight:bold; padding-left:5px;}
        </style>
    </head>
    <body>
    <script>
        // This example adds a search box to a map, using the Google Place Autocomplete
        // feature. People can enter geographical searches. The search box will return a
        // pick list containing a mix of places and predicted search terms.

        function initAutocomplete() {
            var map = new google.maps.Map(document.getElementById('map'), {
                center: {
                    lat: -33.8688,
                    lng: 151.2195
                },
                zoom: 13,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            // Create the search box and link it to the UI element.
            var input = document.getElementById('searchInput');
            var searchBox = new google.maps.places.SearchBox(input);
            map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

            // Bias the SearchBox results towards current map's viewport.
            map.addListener('bounds_changed', function () {
                searchBox.setBounds(map.getBounds());
            });

            var markers = [];
            // [START region_getplaces]
            // Listen for the event fired when the user selects a prediction and retrieve
            // more details for that place.
            searchBox.addListener('places_changed', function () {

                $('#mapContent').html("");

                var places = searchBox.getPlaces();

                if (places.length == 0) {
                    return;
                }

                // Clear out the old markers.
                markers.forEach(function (marker) {
                    marker.setMap(null);
                });
                markers = [];

                // For each place, get the icon, name and location.
                var bounds = new google.maps.LatLngBounds();
                places.forEach(function (place) {
                    var icon = {
                        url: place.icon,
                        size: new google.maps.Size(71, 71),
                        origin: new google.maps.Point(0, 0),
                        anchor: new google.maps.Point(17, 34),
                        scaledSize: new google.maps.Size(25, 25)
                    };

                    // Create a marker for each place.
                    var marker = new google.maps.Marker({
                        map: map,
                        icon: icon,
                        title: place.name,
                        position: place.geometry.location
                    });
                    google.maps.event.addListener(marker, 'click', function (evt) {
                        //document.getElementById('coordinates').value = marker.getPosition().toUrlValue(6);
                        alert(this.placeId)
                    });
                    markers.push(marker);
                    if (place.geometry.viewport) {
                        // Only geocodes have viewport.
                        bounds.union(place.geometry.viewport);
                    } else {
                        bounds.extend(place.geometry.location);
                    }

                    $('#mapContent').append('<ul id="geoData">' +
                    '<li>Full Address: <span id="location">'+ place.formatted_address +'</span></li>'+
                    '<li>Postal Code: <span id="postal_code"></span></li>'+
                    '<li>Country: <span id="country">'+  +'</span></li>'+
                    '<li>Latitude: <span id="lat">'+ place.geometry.location.lat() +'</span></li>'+
                    '<li>Longitude: <span id="lon">'+ place.geometry.location.lng() +'</span></li>'+
                    '<li>Website: <span id="website"></span></li>'+
                    '<li>Contact Number: <span id="number"></span></li>'+
                    '<li>Rating: <span id="rating"></span></li>'+
                    '</ul>');



                });
                map.fitBounds(bounds);
            });
            // [END region_getplaces]
        }

    </script>
    <!--<input id="pac-input" class="controls" type="text" placeholder="Search Box">
    <div id="map"></div>-->

        <div id=wrapper>
            <input id="searchInput" class="controls" type="text" placeholder="Enter a location">
            <div id="map"></div>
            <div id="mapContent">

            </div>
        </div>

    </body>
</html>

Google Maps地点为您提供了参考和ID。 您可以使用该ID来请求其他详细信息。

我将此添加到您的代码中:

// make sure this variable is accesible where you need it (scope)
var service = new google.maps.places.PlacesService(map);

然后,例如网站:

// request details
service.getDetails(place, function(result, status) {
  if (status !== google.maps.places.PlacesServiceStatus.OK) {
    console.error(status);
    return;
  }
  $('#website').html('<a target="_blank" href="'+ result.website +'">'+ result.website +'</a>');
});

您可以获取更多详细信息,请参阅https://developers.google.com/maps/documentation/javascript/places


现在,您面临的另一个问题是ID必须是唯一的! 因此,请勿将其放入foreach循环中。 我的解决方案只会填充首次出现的id =“ website”

places.forEach(function (place) {
  ...
  <span id="website"></span>
  ...
}

您应该先解决此问题,然后再继续。 对于for循环内的所有内容,请使用class而不是id


这是完整的脚本

<script>
    // This example adds a search box to a map, using the Google Place Autocomplete
    // feature. People can enter geographical searches. The search box will return a
    // pick list containing a mix of places and predicted search terms.
    function initAutocomplete() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: {
                lat: -33.8688,
                lng: 151.2195
            },
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        // Create the search box and link it to the UI element.
        var input = document.getElementById('searchInput');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function () {
            searchBox.setBounds(map.getBounds());
        });
        var markers = [];
        // srvice for PLACE details
        var service = new google.maps.places.PlacesService(map);
        // [START region_getplaces]
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function () {
            $('#mapContent').html("");
            var places = searchBox.getPlaces();
            if (places.length == 0) {
                return;
            }
            // Clear out the old markers.
            markers.forEach(function (marker) {
                marker.setMap(null);
            });
            markers = [];
            // For each place, get the icon, name and location.
            var bounds = new google.maps.LatLngBounds();
            places.forEach(function (place) {
                var icon = {
                    url: place.icon,
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(25, 25)
                };
                // Create a marker for each place.
                var marker = new google.maps.Marker({
                    map: map,
                    icon: icon,
                    title: place.name,
                    position: place.geometry.location
                });
                google.maps.event.addListener(marker, 'click', function (evt) {
                    //document.getElementById('coordinates').value = marker.getPosition().toUrlValue(6);
                    alert(this.placeId)
                });
                markers.push(marker);
                if (place.geometry.viewport) {
                    // Only geocodes have viewport.
                    bounds.union(place.geometry.viewport);
                } else {
                    bounds.extend(place.geometry.location);
                }
                $('#mapContent').append('<ul id="geoData">' +
                '<li>Full Address: <span id="location">'+ place.formatted_address +'</span></li>'+
                '<li>Postal Code: <span id="postal_code"></span></li>'+
                '<li>Country: <span id="country">'+  +'</span></li>'+
                '<li>Latitude: <span id="lat">'+ place.geometry.location.lat() +'</span></li>'+
                '<li>Longitude: <span id="lon">'+ place.geometry.location.lng() +'</span></li>'+
                '<li>Website: <span id="website"></span></li>'+
                '<li>Contact Number: <span id="number"></span></li>'+
                '<li>Rating: <span id="rating"></span></li>'+
                '</ul>');
        // request details
                service.getDetails(place, function(result, status) {
                  if (status !== google.maps.places.PlacesServiceStatus.OK) {
                    console.error(status);
                    return;
                  }
                  $('#website').html('<a target="_blank" href="'+ result.website +'">'+ result.website +'</a>');
                });
            });
            map.fitBounds(bounds);
        });
        // [END region_getplaces]
    }
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM