Google地图 - 标记点击时的中心地图 [英] Google Maps - center map on marker click

查看:103
本文介绍了Google地图 - 标记点击时的中心地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在谷歌地图上放置了几个标记的代码如下。

I have the following code for placing several markers on a google map.

我现在要做的是当用户点击放大的标记时,然后将地图集中到标记位置(这是不工作的位 - 朝着setMarkers函数中代码的末尾)。

What I now want to do is when the user clicks on a marker it zooms in and then centers the map to the marker position (this is the bit that's not working - towards the end of the code in the setMarkers function).

有什么想法?

var infowindow = null;
var sites = [];
var partsOfStr = [];
var partsOfStr2 = [];
var bounds;

$(document).ready(function () {
    $("select[id*='coordList']").find("option").each(function () {
        partsOfStr = $(this).val().split(',');
        partsOfStr2 = $(this).text().split('^');
        sites.push([partsOfStr2[0], parseFloat(partsOfStr[0]), parseFloat(partsOfStr[1]), partsOfStr[2], partsOfStr2[1], partsOfStr2[2], partsOfStr2[3], partsOfStr[3], partsOfStr[4], partsOfStr[5]]);
    });
    initialize();
});

function initialize() {
    bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        zoom: 6,
        center: new google.maps.LatLng(54.57951, -4.41387),
        scrollwheel: false,
        mapTypeId: google.maps.MapTypeId.HYBRID
    }

    var map = new google.maps.Map(document.getElementById('map'), mapOptions);

    setMarkers(map, sites);

    infowindow = new google.maps.InfoWindow({
        content: "loading..."
    });

    google.maps.event.addListener(infowindow,'closeclick',function(){
        map.setCenter(new google.maps.LatLng(54.57951, -4.41387));
        map.setZoom(6);
    });

}



function setMarkers(map, markers) {

    for (var i = 0; i < markers.length; i++) {
        var sites = markers[i];
        var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
        var marker = new google.maps.Marker({
            position: siteLatLng,
            map: map,
            title: sites[0],
            html: "<div class='mapDesc'>content here...</div>"
        });

        google.maps.event.addListener(marker, "click", function () {
            infowindow.setContent(this.html);
            infowindow.open(map, this);
            map.setCenter(marker.getPosition()); // NOT WORKING!!!!!!!
            map.setZoom(10);
        });

        bounds.extend(new google.maps.LatLng(sites[1], sites[2]));
        map.fitBounds(bounds);
    }

}


推荐答案

标记指向添加的最后一个标记。使用函数闭包或this就像您为infowindow所做的那样:

marker is left pointing to the last marker added. Either use function closure or "this" like you did for the infowindow:

    google.maps.event.addListener(marker, "click", function () {
        infowindow.setContent(this.html);
        infowindow.open(map, this);
        map.setCenter(this.getPosition()); 
        map.setZoom(10);
    });

这篇关于Google地图 - 标记点击时的中心地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆