html页面遍历map,从HTMLElement获取google.maps.Map实例

goldsky..

23

你可以通过一个小技巧从中获取google.maps.Map对象DOM Element.

初始化地图对象时,需要将对象存储在元素的数据属性中.

例:

$.fn.googleMap = function (options) {

var _this = this;

var settings = $.extend({}, {

zoom: 5,

centerLat: 0,

centerLon: 0

}, options);

this.initialize = function () {

var mapOptions = {

zoom: settings.zoom

};

var map = new google.maps.Map(_this.get(0), mapOptions);

// do anything with your map object here,

// eg: centering map, adding markers' events

/********************************************

* This is the trick!

* set map object to element's data attribute

********************************************/

_this.data('map', map);

return _this;

};

// ... more methods

return this;

};

定义地图元素后,例如:

var mapCanvas = $('#map-canvas');

var map = mapCanvas.googleMap({

zoom: 5,

centerLat: 0,

centerLong: 0

});

// ... add some pre-load initiation here, eg: add some markers

// then initialize map

map.initialize();

然后,您可以使用元素的ID获取地图对象,例如:

var mapCanvas = $('#map-canvas');

$('.location').on('click', function () {

// google map takes time to load, so it's better to get

// the data after map is rendered completely

var map = mapCanvas.data("map");

if (map) {

map.panTo(new google.maps.LatLng(

$(this).data('latitude'),

$(this).data('longitude')

));

}

});

通过使用此方法,您可以在页面上拥有多个具有不同行为的地图.

你可能感兴趣的:(html页面遍历map)