Javascript 自动更新标记位置和信息窗口
我正在解析一个CSV文件,并将线条转换为地图上的标记,在侧边栏上有一个相应的按钮 我当前创建标记的方法是Javascript 自动更新标记位置和信息窗口,javascript,google-maps,Javascript,Google Maps,我正在解析一个CSV文件,并将线条转换为地图上的标记,在侧边栏上有一个相应的按钮 我当前创建标记的方法是 var bounds = new google.maps.LatLngBounds(); var sensor, i, latlng; for (i in sensorList) { // Creates a marker sensor = sensorList[i]; latlng = new google.maps.LatLng(sensor.lat, senso
var bounds = new google.maps.LatLngBounds();
var sensor, i, latlng;
for (i in sensorList) {
// Creates a marker
sensor = sensorList[i];
latlng = new google.maps.LatLng(sensor.lat, sensor.lng);
bounds.extend(latlng);
var marker = createMarker(
latlng, sensor.name, sensor.reading
);
// Creates a sidebar for the marker
createMarkerButton(marker);
}
// Fit to map bounds
mapCanvas.fitBounds(bounds);
我的createMarker函数是
function createMarker(latlng, title, html) {
// Creates a marker
var marker = new google.maps.Marker({
position: latlng,
map: mapCanvas,
title: title
});
// The InfoWindow is opened when the sidebar button is clicked
google.maps.event.addListener(marker, "click", function() {
infoWnd.setContent("<div class = \"PopUp\" style=\"width: 150px; height: 100px;\"<strong>"+title+"</title></strong><br>Latest reading: "+html+"<br><a href=\"\">Full reading</a>");
infoWnd.open(mapCanvas, marker);
});
return marker;
}
函数createMarker(latlng、title、html){
//创建一个标记
var marker=new google.maps.marker({
位置:latlng,
地图:地图画布,
标题:标题
});
//单击侧边栏按钮时,信息窗口打开
google.maps.event.addListener(标记“单击”,函数(){
infoWnd.setContent(建议的第一句话,因为我不完全清楚您的sensorList是一个对象还是一个数组(我怀疑它是一个数组?因为我不明白为什么它会是一个对象),就是不要在数组上使用“for-in”构造,也不要在javascript中创建关联数组仅为对象构造,并在数组上使用“for”或“while”或“do-while”。我这样说有两个原因,一个原因是“for-in”循环实际上是可用循环类型中最慢的,另一个原因是变量类型的可读性(您会看到“for”或“while”或“do-while”循环,您应该能够知道您正在处理一个数组,同样,您看到一个“for-in”循环,您应该能够知道您正在处理一个对象)
通常,清除具有相同属性名称的多个条目的好方法是使用一个对象存储“传感器”对象名称的值,然后检查该对象是否存在相同名称。例如,假设您有一个对象数组:
var sensorList = [ //an array of objects
{name: 'sensorA', propA: 1, propB: 2},
{name: 'sensorB', propA: 3, propB: 4},
{name: 'sensorC', propA: 5, propB: 6},
{name: 'sensorB', propA: 7, propB: 8},
{name: 'sensorA', propA: 9, propB: 10},
{name: 'sensorD', propA: 11, propB: 12}
];
然后创建一个对象,用于筛选现有名称:
var sensorsObj = {};
现在循环浏览传感器列表,并按名称检查每个传感器是否已存在于传感器Sobj中:
for (var sensor, i = 0, len = sensorList.length; i < len; i++) {
sensor = sensorList[i];
if (!sensorsObj[sensor.name]) {
sensorsObj[sensor.name] = 1;
//we know we have not ran across this name yet, so here we can
//create LatLng's, extend bounds, create markers, yada yada yada
}
}
这非常有帮助。谢谢。我对Javascript非常陌生,不知道for in的速度要慢得多,我一定会做出更改。我试图更新标记,但实际上(正如您所指出的)我只需要自下而上,忽略重复的传感器名称。这非常有效。
for (var sensor, i = sensorList.length - 1; i >= 0; i--) {