Google使用多个标记映射多个地图

时间:2013-11-19 16:10:38

标签: javascript google-maps google-maps-api-3

我正在创建一个简单的位置规划,所以基本上每个谷歌地图都会有不同的位置和不同的标记。

所以让我们说googlemap2 =坐标A和googlemap5 =坐标B,我需要每个元素都有一个标记,它在坐标A和B中点击并居中(单独使得坐标B标记永远不会出现在googlemap2中,反之亦然)

到目前为止我的代码是这样的

var map;
var map2;

function initialize(condition) {

//--------------------------------------------------------------------------- TTDI 
if(document.getElementById('googlemap2') !== null){
    var map_canvas = document.getElementById('googlemap2');
    var myLatlng = new google.maps.LatLng(3.140425, 101.632005);
    var mapOptions = {
        center: myLatlng,
        zoom: 11,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(map_canvas, mapOptions);
    TestMarker(myLatlng, map);
}
//--------------------------------------------------------------------------- CHERAS
if(document.getElementById('googlemap5') !== null){
    var map_canvas2 = document.getElementById('googlemap5');
    var myLatlng2 = new google.maps.LatLng(3.140425, 99.632004);
    var mapOptions2 = {
        center: myLatlng2,
        zoom: 11,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map2 = new google.maps.Map(map_canvas2, mapOptions2);
    TestMarker(myLatlng2, map2);
}


}


// Testing the addMarker function
function TestMarker(x,y) {

        var marker = new google.maps.Marker({
        position: x,
        map: y
    });
}

基本上它创造了我想要的东西,只是一个令人讨厌的部分,它总是以第一个元素为中心,所以让我们说它以谷歌地图2的坐标A为中心,googlemap5将有它的标记,但地图的居中将关闭。有任何帮助吗?

1 个答案:

答案 0 :(得分:2)

我会做以下的事情来实现你的目标,让课程更灵活。

var Atlas = (function () {

    Atlas = function (name) {
        this.name = name;
    }

    Atlas.prototype = {
        constructMap: function (options) {
            var _this = this;
            this.map = new google.maps.Map(options.canvas, options.mapOptions);
        },

        addMarker: function (center) {
            var _this = this;
            var marker = new google.maps.Marker({
                position: center,
                map: _this.map
            });
        }
    }

    return Atlas;

})();

var mObj1 = {
    canvas: document.getElementById('map1'),
    mapOptions: {
        center: new google.maps.LatLng(3.140425, 101.632005),
        zoom: 11,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    },
}

var mObj2 = {
    canvas: document.getElementById('map2'),
    mapOptions: {
        center: new google.maps.LatLng(3.140425, 99.632004),
        zoom: 11,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
}

var atlas = new Atlas("atlas");

atlas.constructMap(mObj1);
atlas.addMarker(mObj1.mapOptions.center);
atlas.constructMap(mObj2);
atlas.addMarker(mObj2.mapOptions.center);

我在这里为你做了一个演示:

http://jsfiddle.net/wKtmg/

祝你好运!