getMap not Functioning- Google Maps API v3

时间:2012-11-18 16:50:38

标签: javascript google-maps-api-3

尝试在两个坐标之间绘制折线时,我在使用Google Maps API v3时遇到了setMap函数问题。

我已经通过alert()检查了代码失败的位置,它似乎是在setMap函数中。有没有人有任何想法为什么会发生这种情况?

function showPosition(position)
  {
  lat=position.coords.latitude;
  lon=position.coords.longitude;
  speed= position.coords.speed;
  altitude = position.coords.altitude;


  latlon=new google.maps.LatLng(lat, lon, speed, altitude)
  mapholder=document.getElementById('mapholder')
  mapholder.style.height='250px';
  mapholder.style.width='500px';

  var myOptions={
  center:latlon,zoom:14,
  mapTypeId:google.maps.MapTypeId.ROADMAP,
  mapTypeControl:false,
  navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
  };
  var map=new google.maps.Map(document.getElementById("mapholder"),myOptions);
  var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"});


    x.innerHTML="Latitude: " + lat + " Long: " + lon;
  mapRoute();

  }

function mapRoute(showPosition, position){


var routeCoordinates = [
    new google.maps.LatLng(53.379763, -1.4658453999999999),
    new google.maps.LatLng(21.291982, -157.821856)   
  ];



  var flightPath = new google.maps.Polyline({
    path: routeCoordinates,
    strokeColor: "#FF0000",
    strokeOpacity: 1.0,
    strokeWeight: 2
  });


 flightPath.setMap(map);


}

提前致谢, 马特

1 个答案:

答案 0 :(得分:1)

这是范围问题

var mapfunction showPosition(position)内定义,而不是全局变量

在任何函数调用上方添加var map;,并从var

中删除var map=new google.maps.Map(document.getElementById("mapholder"),myOptions);

然后您应该可以访问map

中的flightPath.setMap(map);