javascript 谷歌地图通过一键式多个标记放大标记

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17775270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:34:38  来源:igfitidea点击:

Google Maps Zoom in on Marker with One Click Multiple Markers

javascriptgoogle-mapsgoogle-maps-api-3google-maps-markersdom-events

提问by Charles Williams

I have read a lot of other posts here on StackOverflow and in Google Search, and I still cannot get this to work correctly. I think it has something to do with my for loop. I already set a mouseover event for the info windows, but what I want is for the map to zoom in on a marker when you click it and center it in the map. I have tried:

我已经在 StackOverflow 和 Google 搜索中阅读了很多其他帖子,但我仍然无法使其正常工作。我认为这与我的 for 循环有关。我已经为信息窗口设置了一个鼠标悬停事件,但是我想要的是当您单击标记并将其在地图中居中时,地图可以放大标记。我努力了:

google.maps.event.addListener(marker,'click',function(e) {
                map.setZoom(9);
                map.setCenter(e.latLng);
            });

Which has worked the best but still doesn't always center on the marker, especially after multiple clicks. Sometimes the marker is not even in view.

哪个效果最好,但仍然不总是以标记为中心,尤其是在多次点击之后。有时标记甚至不在视图中。

The code snippet that I really wanted to use is this:

我真正想使用的代码片段是这样的:

// add the double-click event listener
            google.maps.event.addListener(marker, 'dblclick', function(event){
                map = marker.getMap();

                map.setCenter(overlay.getPosition()); // set map center to marker position
                smoothZoom(map, 12, map.getZoom()); // call smoothZoom, parameters map, final zoomLevel, and starting zoom level
            })


            // the smooth zoom function
            function smoothZoom (map, max, cnt) {
                if (cnt >= max) {
                        return;
                    }
                else {
                    y = google.maps.event.addListener(map, 'zoom_changed', function(event){
                        google.maps.event.removeListener(y);
                        self.smoothZoom(map, max, cnt + 1);
                    });
                    setTimeout(function(){map.setZoom(cnt)}, 80);
                }
            }

Because it is suppose to have smooth zoom. However I can't get this one to work hardly at all. Most clicks on the markers go to Long Island NY or nowhere.

因为它应该具有平滑缩放。但是,我根本无法让这个工作正常。大多数点击标记都指向纽约长岛或无处。

My code follow:

我的代码如下:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
  html { height: 100% }
  body { height: 100%; margin: 0; padding: 0 }
  #map-canvas { height: 100% }
</style>
<script type="text/javascript"
  src="https://maps.googleapis.com/maps/api/js?key=(api)&sensor=false">
</script>
<script type="text/javascript">
google.maps.visualRefresh = true;

function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(42, -97),
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var jobs = [
        ['Taylor', 'Texas', 30.570155, -97.409649, 'machine install and training'],
        ['Fort Riley', 'Kansas', 39.104172, -96.735558, 'machine install and training'],
        ['Toronto', 'Ontario, Canada', 43.653226, -79.383184, 'machine install and training'],
        ['Spokane', 'Washington', 47.658780, -117.426047, 'Machine install and training'],
        ['New Paris', 'Indiana', 41.504848, -85.826487, 'machine install'],
        ['Charleston', 'Mississippi', 34.00711, -90.055194, 'machine install and training'],
        ['Tinley Park', 'Illinois', 41.596405, -87.785119, 'training.'],
        ['Savannah', 'Georgia', 32.08078, -81.090719, 'machine install and training'],
        ['Long Island', 'New York', 40.852505, -73.135849, 'Machine install and training']
    ];

    var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

    var infoWindow = new google.maps.InfoWindow;

        for (var i = 0; i < jobs.length; i++) {
            var city = jobs[i][0];
            var state = jobs[i][1];
            var lat = jobs[i][2];
            var lng = jobs[i][3];
            var desc = jobs[i][4];
            var z = i;
            var myLatLng = new google.maps.LatLng(lat, lng);

            var content = '<div class="map-content"><h3>' + city + ', ' + state +
                 '</h3>' + desc + '</div>';

            var marker = new google.maps.Marker({
                map: map,
                title: city + state,
                position: myLatLng,
                zIndex: z
            });

            google.maps.event.addListener(marker, 'mouseover', (function(marker, content) {
                return function() {
                    infoWindow.setContent(content);
                    infoWindow.open(map, marker);
                }
            })(marker, content));

            // add the double-click event listener
            google.maps.event.addListener(marker, 'dblclick', function(event){
                map = marker.getMap();

                map.setCenter(overlay.getPosition()); // set map center to marker position
                smoothZoom(map, 12, map.getZoom()); // call smoothZoom, parameters map, final zoomLevel, and starting zoom level
            })


            // the smooth zoom function
            function smoothZoom (map, max, cnt) {
                if (cnt >= max) {
                        return;
                    }
                else {
                    y = google.maps.event.addListener(map, 'zoom_changed', function(event){
                        google.maps.event.removeListener(y);
                        self.smoothZoom(map, max, cnt + 1);
                    });
                    setTimeout(function(){map.setZoom(cnt)}, 80);
                }
            }
        }
}

  google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
    <div id="map-canvas"/>
</body>
</html>

If I remove the code for attempting a zoom click event and take it out of the loop, it only works for my long island marker (since that is the last information in the array that is processed). Any help on how to get this to center on the markers on click would be great. I can't really find anything searching that has been implemented on arrays and loops. I am new to the Google API, and I have only done basic Javascript on top of that.

如果我删除尝试缩放单击事件的代码并将其从循环中取出,则它仅适用于我的长岛标记(因为这是处理的数组中的最后一个信息)。关于如何在点击时将其置于标记中心的任何帮助都会很棒。我真的找不到任何已经在数组和循环上实现的搜索。我是 Google API 的新手,除此之外我只做过基本的 Javascript。

EDIT: An example of this is here.

编辑:这里有一个例子。

回答by devbnz

Looks like you have a scope problem.

看起来你有一个范围问题。

Try this as eventlistener:

试试这个作为事件监听器:

google.maps.event.addListener(marker, 'click', function() {
map.panTo(this.getPosition());
});  

this works here:

这在这里工作:

http://jsfiddle.net/iambnz/mQEwh/

http://jsfiddle.net/iambnz/mQEwh/

回答by RyanW

Try This to get the smoothZoom to work:

试试这个让smoothZoom工作:

Remove the "self" from the line in the smoothZoom function i.e

从 smoothZoom 函数中的行中删除“self”,即

else {
                y = google.maps.event.addListener(map, 'zoom_changed', function(event){
                    google.maps.event.removeListener(y);
                    smoothZoom(map, max, cnt + 1);

Basically It wasn't working for me, so I brought up the error console on my browser and so it was erroring at this point saying that self.smoothZoom wasn't a function.

基本上它对我不起作用,所以我在我的浏览器上打开了错误控制台,所以此时它出错了,说 self.smoothZoom 不是一个函数。

I removed the "self" and it works. Had some playing to do with the setTimeout variable to make it smoother. But at least it works :)

我删除了“自我”并且它有效。有一些玩弄 setTimeout 变量以使其更流畅。但至少它有效:)