Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Google Maps places API-如何在多个结果上使用Google地图搜索框获取国家、邮政编码、号码、网站URL_Javascript_Google Maps_Google Maps Api 3 - Fatal编程技术网

Javascript Google Maps places API-如何在多个结果上使用Google地图搜索框获取国家、邮政编码、号码、网站URL

Javascript Google Maps places API-如何在多个结果上使用Google地图搜索框获取国家、邮政编码、号码、网站URL,javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,我正在使用谷歌地图搜索框和谷歌地图的地方API,以获得多个结果,如商店和地方等 它的工作很好,我得到的地址和经纬度,但我如何才能得到其余的细节,如果可以像国家,邮政编码,网站网址,联系电话和评级 这是我的代码,任何帮助或建议都将不胜感激 <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integr

我正在使用谷歌地图搜索框和谷歌地图的地方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>


Google Maps places为您提供了一个参考信息和一个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>');
});
//请求详细信息
service.getDetails(位置、功能(结果、状态){
if(status!==google.maps.places.PlacesServiceStatus.OK){
控制台错误(状态);
返回;
}
$(“#网站”).html(“”);
});
您可以获取更多详细信息,请参阅


现在,你们面临的另一个问题是,ID必须是唯一的!!! 所以你不能把它放在foreach循环中。我的解决方案将只填写id=“网站”的第一次出现

places.forEach(函数(位置){
...
...
}
在继续之前,您应该首先解决这个问题。对于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>

//本例使用Google Place Autocomplete将搜索框添加到地图中
//功能。用户可以输入地理搜索。搜索框将返回
//包含位置和预测搜索词组合的拾取列表。
函数initAutocomplete(){
var map=new google.maps.map(document.getElementById('map'){
中心:{
lat:-33.8688,
液化天然气:151.2195
},
缩放:13,
mapTypeId:google.maps.mapTypeId.ROADMAP
});
//创建搜索框并将其链接到UI元素。
var input=document.getElementById('searchInput');
var searchBox=newgoogle.maps.places.searchBox(输入);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(输入);
//将搜索框结果偏向当前地图的视口。
map.addListener('bounds_changed',function(){
searchBox.setBounds(map.getBounds());
});
var标记=[];
//srvice用于获取位置详细信息
var service=newgoogle.maps.places.PlacesService(地图);
//[开始区域\u getplaces]
//侦听用户选择预测并检索时激发的事件
//关于那个地方的更多细节。
searchBox.addListener('places\u changed',函数(){
$('#mapContent').html(“”);
var places=searchBox.getPlaces();
如果(places.length==0){
返回;
}
//清除旧的标记。
markers.forEach(函数(marker){
marker.setMap(空);
});
标记=[];
//对于每个位置,获取图标、名称和位置。
var bounds=new google.maps.LatLngBounds();
地点。forEach(功能(地点){
变量图标={
url:place.icon,
大小:新谷歌地图大小(71,71),
来源:新google.maps.Point(0,0),
主播:新google.maps.Point(17,34),
scaledSize:new google.maps.Size(25,25)
};
//为每个地方创建一个标记。
var marker=new google.maps.marker({
地图:地图,
图标:图标,
标题:place.name,
位置:place.geometry.location
});
google.maps.event.addListener(标记,'click',函数(evt){
//document.getElementById('coordinates').value=marker.getPosition().TourValue(6);
警报(this.placeId)
});
标记器。推(标记器);
if(place.geometry.viewport){
//只有地理代码具有视口。
联合(place.geometry.viewport);
}否则{
扩展(place.geometry.location);
}
$('#mapContent')。追加('
    '+ “
  • 完整地址:”+place.formatted_Address+“
  • ”+ “
  • 邮政编码:
  • ”+ “
  • 国家:”++“
  • ”+ “
  • 纬度:”+place.geometry.location.lat()+“
  • ”+ “
  • 经度:”+place.geometry.location.lng()+“
  • ”+ “
  • 网站:
  • ”+ “
  • 联系电话:
  • ”+ “
  • 评级:
  • ”+ “
”); //请求详细信息 service.getDetails(位置、功能(结果、状态){ if(status!==google.maps.places.PlacesServiceStatus.OK){ 控制台错误(状态); 返回; } $(“#网站”).html(“”); }); }); 映射边界(bounds); }); //[结束区域\u getplaces] }
Google Maps places为您提供了一个参考和一个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>');
});
//请求详细信息
service.getDetails(位置、功能(结果、状态){
if(status!==google.maps.places.PlacesServiceStatus.OK){
控制台错误(状态);
返回;
}
$(“#网站”).html(“”);
});
您可以获取更多详细信息,请参阅


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

places.forEach(函数(位置){
...
...
}
<