javascript - Google 将 API 在 map 上放置多个标记并缩放到大多数标记所在的位置

标签 javascript arrays google-maps-api-3 google-places-api

首先我想向你们展示我已经尝试过的解决方案,所以你们也不要使用它们:

  1. placing multiple markers on google map from array .
  2. placing multiple markers on a google map .

因为我在这些地方有以下循环:

service.textSearch({query:query}, function(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        //for each result in results.length ++
        for (var i = 0; i < results.length; i++) {
            //here I'm just setting the names from the variables into a list, to display the names as I show in (Figure 1).
            var item = document.createElement('li');
            item.appendChild(document.createTextNode(results[i].name));
            document.getElementById('results').appendChild(item);

            //here I set my variables that are necessary for the markers to work
            p_id[i] = results[i].place_id;

            lat[i] = results[i].geometry.location.lat();
            lng[i] = results[i].geometry.location.lng();

            //here I initialize the map with the given values.
            initMap(p_id, lat, lng, i);
        }
    }
});
<小时/>

图 1: Figure 1

<小时/>

当此循环完成时,它将转到在 map 上放置标记的位置。

注意:我不想删除它再次创建的地方,因为它对我来说非常有用,而且它似乎也没有阻碍我想做的事。

至于 map 本身上的标记放置器:

function initMap(p_id, lat, lng, i) {
    //this creates the position of the map
    var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: lat[i], lng: lng[i]},
        zoom: 13
    });

    var infowindow = new google.maps.InfoWindow(), marker, i;
    var service = new google.maps.places.PlacesService(map);

    var marker;

    //gets the details of the placeid over again
    service.getDetails({
        placeId: p_id[i]
    }, function(place, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {

            //this is where the marker is created with position and animation
            marker = new google.maps.Marker({
                animation: google.maps.Animation.DROP,
                position: new google.maps.LatLng(lat[i], lng[i]),
                map: map
            });

            //this is the info if you click the marker
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {
                    infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + 'Place ID: ' + place.place_id + '<br>' + place.formatted_address + '</div>');
                    infowindow.open(map, marker);
                }
            })(marker, i));
        }
    });
}

奇怪的是,如果只有 1 个位置,则显示 1 个标记,但当它们有更多位置时,则根本没有标记...正如我在 图 2 中所示

<小时/>

图 2: Figure 2

<小时/>

如果有人有任何线索可以解决这个问题,请告诉他们。可悲的是,我自己似乎无法弄清楚,尽管我已经寻找了一段时间。我尝试制作一个 Jsfiddle,但遗憾的是 API 无法在 jsfddle 上运行...

<小时/>

编辑:

多标记问题已由 SeanKendle 解决。问题就好像我已经怀疑我一直在创建多个 map ......

我只是将 maps 从我的 mapinit 函数中移出,并将其放置在 getPlaces 中的 service 之上功能如下:

var map = new google.maps.Map(document.getElementById('map'), {
    center: latlng,
    zoom: 5
});

service = new google.maps.places.PlacesService(
  document.getElementById('attributions') //attributions-container
);

//send a query
service.textSearch({query:query}, function(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
            var item = document.createElement('li');
            item.appendChild(document.createTextNode(results[i].name));
            document.getElementById('results').appendChild(item);

            p_id[i] = results[i].place_id;

            lat[i] = results[i].geometry.location.lat();
            lng[i] = results[i].geometry.location.lng();

            initMap(p_id, lat, lng, i, map);
        }
    }
});
<小时/>

现在我面临的最后一个问题是我需要放大标记最多的地方。现在我只是简单地设置它应该开始的纬度和经度,如下所示:

var latlng = new google.maps.LatLng(20.540221, -4.042969);

预先感谢!

<小时/>

最佳答案

请仔细阅读我的评论。我可能错过了一些事情,我在工作中很着急。我简化了您的大量代码并删除了一些额外的服务调用等。

编辑:我添加了一个 map 边界变量来在放置标记后设置 map 缩放和中心

编辑 2:我添加了 Google map 回调函数,以消除导致您无法访问 google 命名空间的竞争条件。请务必替换 YOUR_API_KEY

首先,将实际的 map 初始化移出循环:

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

<script>
    var startLatLng, //change this to some value near to where the map will end up
        allMarkers = [], //keep a global copy of your markers
        mapPointsBounds = [], //map bounds of all markers
        map; //copy of the map

    //Google will call this when it's ready, it's a query string in the script tag above `&callback=initMap`:
    function initMap() {
        startLatLng = new google.maps.LatLng([0, 0]);
        mapPointsBounds = new google.maps.LatLngBounds();

        map = new google.maps.Map(document.getElementById('map'), {
            center: startLatLng,
            zoom: 13
        });

        service.textSearch({query:query}, function(results, status) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                //for each result in results.length ++
                for (var i = 0; i < results.length; i++) {
                    //here I'm just setting the names from the variables into a list, to display the names as I show in (Figure 1).
                    var item = document.createElement('li');
                    item.appendChild(document.createTextNode(results[i].name));
                    document.getElementById('results').appendChild(item);

                    //let's just send the object, this is unnecessary:
                    //here I set my variables that are necessary for the markers to work
                    //p_id[i] = results[i].place_id;
                    //lat[i] = results[i].geometry.location.lat();
                    //lng[i] = results[i].geometry.location.lng();

                    //Change this function name to "addMapMarker", send in the results object
                    addMapMarker(results[i], i);
                }

                //finally, fitBounds on map to set zoom and center:
                map.fitBounds(mapPointsBounds);
            }
        });
    }

    //I would change the name of this function to "addMapMarker" or something similar
    function addMapMarker(markerInfo, i) {
        //why are you initializing "i" again if you're passing it in?
        var infowindow = new google.maps.InfoWindow(), marker; //, i;
        var service = new google.maps.places.PlacesService(map);

        var marker;

        //gets the details of the placeid over again - why?  Why not send the info into the function?
        /* Is this really necessary again?
        service.getDetails({
            placeId: markerInfo.place_id
        }, function(place, status) {
            if (status === google.maps.places.PlacesServiceStatus.OK) {
        */
        //this is where the marker is created with position and animation
        marker = new google.maps.Marker({
            animation: google.maps.Animation.DROP,
            position: markerInfo.geometry.location,
            map: map,
            markerInfo: markerInfo //you can store anything in the map point
        });

        allMarkers.push(marker); //keeping all markers in an array
        mapPointsBounds.extend(markerInfo.geometry.location); //extend bounds to contain this marker


        //this is the info if you click the marker
        //you're running a function, then returning a function... just put a simple function here:
        google.maps.event.addListener(marker, 'click', function (marker, i) {
            //return function() {
            infowindow.setContent('<div><strong>' + marker.markerInfo.name + '</strong><br>' + 'Place ID: ' + marker.markerInfo.place_id + '<br>' + marker.markerInfo.formatted_address + '</div>');
            infowindow.open(map, marker);
            //}
        });
    }
</script>

关于javascript - Google 将 API 在 map 上放置多个标记并缩放到大多数标记所在的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43739876/

相关文章:

javascript - 在滚动条上将 div 淡化为黑色

arrays - 选择模式元素与规则匹配的数组排列

python - 如何在 python 中打印出 calendar.month_name 数组?

javascript - 编写 javascript :void(0)? 的更好方法是什么

javascript - Node.js - 重新创建 navigator.onLine

javascript - Grunt- Mocha ​​ `PhantomJS timed out`

javascript - 将字符串拆分为具有交替一位和两位数字的数组

javascript - 被 map 图 block chop 的符号

javascript - 什么时候加载谷歌地图?

javascript - 如何在 jquery 选项卡中加载我的谷歌地图?