谷歌地图放置API - 如何使用谷歌地图搜索框获取多个结果的国家,邮政编码,数字,网站URL

时间:2017-02-01 08:02:23

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

我正在使用谷歌地图搜索框与谷歌地图放置API,以获得多个结果,如商店和地方等。

它工作正常,我正在获取地址和纬度 - 经度但如何获得其他详细信息,如国家,邮政编码,网站网址,联系电话和评级。

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

    <!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>

1 个答案:

答案 0 :(得分:1)

Google地图位置为您提供参考和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-loops

中的所有内容都使用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>