2012-11-18 70 views
0

我試圖在兩個座標之間繪製多段線時,在使用Google Maps API v3的setMap函數時遇到問題。getMap無法運行 - Google Maps API v3

我檢查了代碼與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

這是一個範圍問題

var map被內部限定的function showPosition(position)而不是作爲一個全局變量

添加var map;上述任何函數調用並從var map=new google.maps.Map(document.getElementById("mapholder"),myOptions);刪除var

那麼你應該可以訪問map裏面flightPath.setMap(map);

+0

沒問題很高興我可以幫忙 –