2015-08-13 46 views
-2

为了加一个偏移量在谷歌地图的中心点当按钮被按下,我试试这个funcion:传递地图对象的JavaScript功能

function offsetCenter(map, marker) { 

var worldCoordinateCenter = map.getProjection().fromLatLngToPoint(marker.getPosition()); 
var pixelOffset = new google.maps.Point((100/scale) || 0,(0/scale) ||0) 

var worldCoordinateNewCenter = new google.maps.Point(
    worldCoordinateCenter.x - pixelOffset.x, 
    worldCoordinateCenter.y + pixelOffset.y 
); 

var newCenter = map.getProjection().fromPointToLatLng(worldCoordinateNewCenter); 

map.setCenter(newCenter); 

} 


}); 

我打电话从信息窗口,其中的地图和标志物funcion被定义为:

 (function(marker, data) { 
       google.maps.event.addListener(marker, "click", function() { 

      info = '<h4>' + data.nombre + '</h4><h4>'+ data.offerta+'</h4><h4>'+ data.horario+'</h4><a href='+data.web+'><h4>Web</h4></a>' 
+ '<input type="button" class = "launchConfirm" onclick="offsetCenter(\''+map+'\', \''+marker+'\');" value='Reset center'></input>' //this is the button inside the infowindos to re-set the map center with an offset 
     ; 

     infoWindow.setContent(info); 
     infoWindow.open(map, marker); 

     map.setCenter(marker.getPosition()); //center the map to marker 
     map.setZoom(16);      //zoom to marker 

     }); 
     } 

但是marker和map对象没有在offsetCenter函数内部定义。 如何将地图对象和标记传递给该函数?

+0

请提供一个[最小,**完整**,测试和可读示例](http://stackoverflow.com/help/mcve),演示您正在尝试修复的问题。 – geocodezip

+0

我只是在里面添加完整的infowindows函数,调用“offsetCenter”函数的按钮被调用。 – doxsi

回答

0
  1. 确保您的'地图'变量和您的标记管理器在范围> =功能范围内。这样你就不需要传入地图。

  2. 使用标记管理器来管理您的制造商。你可以在你的链接上添加一个唯一的id给某个属性。当点击进入时,您可以访问该对象以获取该ID,这将允许您从经理中检索制造商。所以代码会是这个样子:

信息窗口内容(简称为简洁起见):

var info = '<h4>' + data.nombre + '</h4>'<input type="button" data-markerId="' + SomeMarkerManager.getMarkerId() '" onclick="offsetCenter(this);" value='Reset center'></input>' 


var offsetCenter = function (element) { 
    // get the marker Id 
    var markerId = $(element).attr("data-marker-id"); 

    // use the markerId to find your marker 
    var marker = SomeMarkerManager.getMarkerById(markerId); 

    // now you have access to your map and the clicked marker 
} 

附: 标记管理器超出了此答案的范围。只需搜索谷歌地图标记管理器。