谷歌地图onclick转到地图上的标记

时间:2014-02-04 01:44:52

标签: google-maps

当点击“在地图上查看”链接时,我在尝试让我的地图转到某个位置的标记时遇到问题。我一直收到错误“TypeError:map.setOptions不是函数”。

以下是代码:

var infowindow = null;
function initialize(){
  var myOptions = {
    zoom:3,
    center:new google.maps.LatLng(0,0),
    mapTypeId:google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(
    document.getElementById('map'),myOptions);
    setMarkers(map,sites);
  }
  var infowindow = new google.maps.InfoWindow({
    content:'Loading...'
  });
  var sites = [
    ['GIC Campers Sydney',-33.935477,151.012108,1,'xxx'],
    ['GIC Campers Brisbane',-27.5445735,153.0139405,1,'yyy'],
    ['GIC Campers Melbourne',-37.650735,144.940551,1,'zzz']
  ];
  function setMarkers(map,markers){
    var bounds = new google.maps.LatLngBounds();
    var image = new google.maps.MarkerImage('/templates/home/images/google-pin.png',
      new google.maps.Size(60,60),
      new google.maps.Point(0,0),
      new google.maps.Point(30,60));
    for(var i=0;i<markers.length;i++){
      var sites = markers[i];
      var siteLatLng = new google.maps.LatLng(sites[1],sites[2]);
      var marker = new google.maps.Marker({
        position:siteLatLng,
        map:map,
        icon:image,
        title:sites[0],
        zIndex:sites[3],
        html:sites[4]
      });
      google.maps.event.addListener(marker,'click',function(){
        map.setZoom(15);
        map.setCenter(marker.getPosition());
        infowindow.setContent(this.html);
        infowindow.open(map,this);
      });
    bounds.extend(siteLatLng);
    map.fitBounds(bounds);
  }
};
function loadcity(which){
  initialize();
  if(which == 'gic-campers-sydney'){
    var newPos = new google.maps.LatLng(-33.935477,151.012108);
    map.setOptions({center:newPos,zoom:15});
  }
  if(which == 'gic-campers-brisbane'){
    var newPos = new google.maps.LatLng(-27.5445735,153.0139405);
    map.setOptions({center:newPos,zoom:15});
  }
  if(which == 'gic-campers-melbourne'){
    var newPos = new google.maps.LatLng(-37.650735,144.940551);
    map.setOptions({center:newPos,zoom:15});
  }
}
jQuery(document).ready(function(e) {
  initialize();
  jQuery('.updatemap').click(function(e){
    e.preventDefault();
  });
});

和一个示例链接:

<a onclick="loadcity('gic-campers-brisbane');" class="updatemap" href="#gic-campers-brisbane">View on map</a>

对此的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您的地图变量是初始化函数的本地变量。它在loadcity函数中不可用。

一个解决方法是使其全局化(如您的信息窗口):

var infowindow = null;
var map = null;
function initialize(){
  var myOptions = {
    zoom:3,
    center:new google.maps.LatLng(0,0),
    mapTypeId:google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(
    document.getElementById('map'),myOptions);
    setMarkers(map,sites);
  }

不确定为什么要重新创建地图(每次loadcity运行时调用initialize()),你真的应该只需要这样做一次。