【发布时间】:2014-02-10 23:02:10
【问题描述】:
嘿,我正在尝试在我的 MeteorJS 项目中使用谷歌地图,以便在所有客户的地图上显示谷歌地图,然后在您单击其中一个标记时显示一个 infoWindow。
问题是任何时候你点击它都会从头开始重新渲染地图的标记,我知道这与点击 infoWindow 时设置的 Session 变量的反应性有关。
有什么办法可以避免在会话变量发生变化时重新渲染地图?
谢谢。
下面是我项目中使用的 JS 和模板。
<template name="customers_map">
{{#constant}}
<div id="mapWrapper">
<div id="map-canvas"></div>
</div>
{{/constant}}
</template>
制作谷歌地图和标记的代码。
Template.customers_map.rendered = function() {
$("#map-canvas").height("400px");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
Session.set("myLat", p.coords.latitude);
Session.set("myLng", p.coords.longitude);
});
}
Deps.autorun(function(){
var mapOptions = {
center: new google.maps.LatLng(Session.get("myLat"), Session.get("myLng")),
zoom: 15,
zoomControl: true,
zoomControlOptions: {style: google.maps.ZoomControlStyle.SMALL},
streetViewControl: false,
mapTypeControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.SMALL
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var infowindow = new google.maps.InfoWindow({
content: Template.customers_infoWindow()
});
Customers.find().forEach(function(customer) {
if (customer.loc != null) {
var geo = customer.geoLocation();
var marker = new google.maps.Marker({
position: new google.maps.LatLng(geo.lat, geo.lng),
title: customer.name(),
icon:'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
Session.set("customerId", customer._id);
infowindow.open(map,marker);
});
} else {
console.log(customer.name() + " has no geoLocation");
};
});
});
};
infoWindow 模板
<template name="customers_infoWindow">
<h1>{{record.name}}</h1>
</template>
以及 infoWindow 模板的 js
Template.customers_infoWindow.record = function() {
return Customers.findOne({_id: Session.get("customerId")});
}
【问题讨论】: