【问题标题】:Google Maps API Finding DetailsGoogle Maps API 查找详情
【发布时间】:2021-10-30 18:22:24
【问题描述】:

我正在尝试使用有关位置的谷歌地图详细信息从标记显示在信息窗口中。我正在创建一个标记,并希望获取该标记的地址,以便将其存储在数据库中。我能够获得标记的标题,但我不知道如何获得完整地址。这是我的代码:

<script>

    let pos;
    let map;
    let bounds;
    let infoWindow;
    let currentInfoWindow;
    let service;
    let infoPane;
    function initMap() {

        bounds = new google.maps.LatLngBounds();
        infoWindow = new google.maps.InfoWindow;
        currentInfoWindow = infoWindow;

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(position => {
                pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };

                map = new google.maps.Map(document.getElementById('map'), {
                    center: pos,
                    zoom: 20
                });
                bounds.extend(pos);

                infoWindow.setPosition(pos);
                infoWindow.setContent('Location found.');
                infoWindow.open(map);
                map.setCenter(pos);


                getNearbyPlaces(pos);
            }, () => {

                handleLocationError(true, infoWindow);
            });
        } else {

            handleLocationError(false, infoWindow);
        }
    }


    function handleLocationError(browserHasGeolocation, infoWindow) {

        pos = { lat: -33.856, lng: 151.215 };
        map = new google.maps.Map(document.getElementById('map'), {
            center: pos,
            zoom: 20
        });


        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
            'Geolocation permissions denied. Using default location.' :
            'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
        currentInfoWindow = infoWindow;

        getNearbyPlaces(pos);
    }

    function getNearbyPlaces(position) {
        let request = {
            location: position,
            rankBy: google.maps.places.RankBy.DISTANCE,
            keyword: 'basketball courts'
        };

        service = new google.maps.places.PlacesService(map);
        service.nearbySearch(request, nearbyCallback);
    }

    function nearbyCallback(results, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
            createMarkers(results);
        }
    }


    function createMarkers(places) {
        places.forEach(place => {
            let marker = new google.maps.Marker({
                position: place.geometry.location,
                map: map,
                title: place.name
            });

            marker.addListener("click", () => {
                map.setZoom(16);
                map.setCenter(marker.getPosition());
            });
            bounds.extend(place.geometry.location);
        });

        map.fitBounds(bounds);
    }


</script>

<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB4mivUi9qIAPD1PUxQwFfwA0ttCbNcATw&libraries=places&callback=initMap">
</script>

我不熟悉 javascript,所以我不确定如何格式化它。如果它显示在信息窗口中,我可以从那里自己处理它,但如果有人对如何在那里显示它有任何建议,我将不胜感激。

【问题讨论】:

    标签: javascript api google-maps


    【解决方案1】:

    公平地说,您已经完成了大部分工作,但如果只是从nearbyPlaces 搜索中获取结果并添加到信息窗口中,那么您可能会在下面找到用途。工作在createMarkers函数中完成

    <!doctype html>
    <html lang='en'>
        <head>
            <meta charset='utf-8' />
            <title>Google Maps: </title>
            <style>
                #map{
                    width:800px;
                    height:600px;
                    float:none;
                    margin:auto;
                }
            </style>
        </head>
        <body>
            <div id='map'></div>
            <script>
    
                let pos;
                let map;
                let bounds;
                let infoWindow;
                let currentInfoWindow;
                let service;
                let infoPane;
                
                
                
                function initMap() {
    
                    bounds = new google.maps.LatLngBounds();
                    infoWindow = new google.maps.InfoWindow;
                    currentInfoWindow = infoWindow;
    
                    if (navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(position => {
                            pos = {
                                lat: position.coords.latitude,
                                lng: position.coords.longitude
                            };
    
                            map = new google.maps.Map(document.getElementById('map'), {
                                center: pos,
                                zoom: 20
                            });
                            bounds.extend(pos);
    
                            infoWindow.setPosition(pos);
                            infoWindow.setContent('Location found.');
                            infoWindow.open(map);
                            map.setCenter(pos);
    
    
                            getNearbyPlaces( pos );
                        }, () => {
    
                            handleLocationError(true, infoWindow);
                        });
                    } else {
    
                        handleLocationError(false, infoWindow);
                    }
                }
    
    
                function handleLocationError(browserHasGeolocation, infoWindow) {
                    pos = { lat: -33.856, lng: 151.215 };
                    map = new google.maps.Map(document.getElementById('map'), {
                        center: pos,
                        zoom: 20
                    });
                    infoWindow.setPosition(pos);
                    infoWindow.setContent(browserHasGeolocation ?
                        'Geolocation permissions denied. Using default location.' :
                        'Error: Your browser doesn\'t support geolocation.');
                    infoWindow.open(map);
                    currentInfoWindow = infoWindow;
                    getNearbyPlaces(pos);
                }
    
                function getNearbyPlaces(position) {
                    let request = {
                        location: position,
                        rankBy: google.maps.places.RankBy.DISTANCE,
                        keyword: 'basketball courts'
                    };
                    service = new google.maps.places.PlacesService(map);
                    service.nearbySearch(request, nearbyCallback);
                }
    
                function nearbyCallback(results, status) {
                    if (status === google.maps.places.PlacesServiceStatus.OK) {
                        createMarkers(results);
                    }
                }
    
    
                function createMarkers(places) {
                    places.forEach(place => {
                        
                        console.log(place)
                        
                        let marker = new google.maps.Marker({
                            position: place.geometry.location,
                            map: map,
                            title:place.name,
                            /* assign the response data as a property of the marker */
                            content:place
                        });
                        
                        /* 
                            for convenience a regular anonymous function is better here 
                            as it allws us to use `this` to refer to the marker itself
                            within the body of the function.
                        */
                        marker.addListener("click", function(e){
                            map.setZoom(16);
                            map.setCenter( marker.getPosition() );
                            
                            /* 
                                Iterate through ALL properties ( or just some ) of the `this.contents` 
                                property and set as the content for the infowindow
                            */
                            infoWindow.setContent( Object.keys(this.content).map(k=>{
                                return [k,this.content[k] ].join('=')
                            }).join( String.fromCharCode(10) ) );
                            /* open the infowindow */
                            infoWindow.setPosition(e.latLng)
                            infoWindow.open(map,this);
                        });
                        bounds.extend(place.geometry.location);
                    });
    
                    map.fitBounds(bounds);
                }
    
    
            </script>
    
            <script async defer src="//maps.googleapis.com/maps/api/js?key=<APIKEY>&libraries=places&callback=initMap">
            </script>
        </body>
    </html>
    

    返回的数据是 JSON,每个单独的结果都有这样的结构。其中包含的位置数据与运行此相同脚本的其他人发现的位置数据没有任何相似之处,但已足够。

      {
         "business_status" : "OPERATIONAL",
         "geometry" : {
            "location" : {
               "lat" : 52.7525688,
               "lng" : 0.4036446
            },
            "viewport" : {
               "northeast" : {
                  "lat" : 52.75354047989272,
                  "lng" : 0.4048724298927222
               },
               "southwest" : {
                  "lat" : 52.75084082010728,
                  "lng" : 0.4021727701072778
               }
            }
         },
         "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/generic_business-71.png",
         "icon_background_color" : "#7B9EB0",
         "icon_mask_base_uri" : "https://maps.gstatic.com/mapfiles/place_api/icons/v2/generic_pinlet",
         "name" : "Multi-Use Games Area",
         "place_id" : "ChIJX2Y4mjyL10cRQ0885NSSeTE",
         "plus_code" : {
            "compound_code" : "QC33+2F King's Lynn",
            "global_code" : "9F42QC33+2F"
         },
         "rating" : 0,
         "reference" : "ChIJX2Y4mjyL10cRQ0885NSSeTE",
         "scope" : "GOOGLE",
         "types" : [ "point_of_interest", "establishment" ],
         "user_ratings_total" : 0,
         "vicinity" : "The Walks, nr, South St, King's Lynn"
      }
    

    在标记点击回调函数中,之前是这样的:

    infoWindow.setContent( Object.keys(this.content).map(k=>{
        return [k,this.content[k] ].join('=')
    }).join( String.fromCharCode(10) ) );
    

    我们可以构建一串您希望使用的任何项目:

    infoWindow.setContent( this.content.name ); // simply display the name
    

    infoWindow.setContent(
        `<h1>${this.content.name}</h1>
        <p>${this.content.vicinity}</p>
        <ul>
            <li>Lat: ${this.content.geometry.location.lat()}</li>
            <li>Lng: ${this.content.geometry.location.lng()}</li>
        </ul>
        <img src="${this.content.icon}" />`
    ); // show some HTML content
    

    【讨论】:

    • 非常感谢!你知道如何过滤信息吗,因为现在它只是一堆我不需要的信息。我真的只是想要地址和place_id。如果没有,你已经做得足够了
    • 添加到标记的内容只是通过迭代来生成您看到的显示,但是为了将单个元素与数据隔离开来,我将更新答案以显示示例。也许然后接受答案?!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 2014-07-01
    • 2016-06-08
    • 1970-01-01
    相关资源
    最近更新 更多