未捕获的TypeError:无法读取属性' setMap'为null

时间:2015-05-21 11:28:56

标签: javascript google-maps google-maps-api-3

下面你好我得到了绘制折线的代码,并从列表中获取分段颜色。它工作正常,我想在单击按钮时删除此折线,每当我调用该函数时我都会收到此错误:" Uncaught TypeError:无法读取属性' setMap' of null"

代码:

var map;
var PathStyle;

function initialize() {

var mapDiv = document.getElementById('testerbuttons');
google.maps.event.addDomListener(mapDiv, 'click', showAlert);

$.getJSON("http://whatever.com/test.php", function(roads){
var routeseg=Object.keys(roads).length;
var arr1=[];
var filarr=[]
var router=[];
var colorarray=[]
for (i = 0; i < routeseg; i++) { 
var x=0;
    $.each(roads[i], function(key, value){
    (filarr[x]=value); 
    arr1[i]=new google.maps.LatLng(filarr[3], filarr[4]);
    colorarray[i]=filarr[5];
    x=x+1;
    });
}

for (var i = 0; i < arr1.length-1; i++) {
PathStyle = new google.maps.Polyline({
     path: [arr1[i], arr1[i+1]],
     strokeColor:colorarray[i],
     strokeOpacity: 1.0,
    strokeWeight: 8,
    map: map
    });
}});


  var mapOptions = {
zoom: 20,
center: new google.maps.LatLng(30.0085, 30.9825)};

  var map = new google.maps.Map(document.getElementById('map-canvas'),
  mapOptions);}

 function showAlert(){
    PathStyle.setMap(null);
    }

 google.maps.event.addDomListener(window, 'load', initialize);

1 个答案:

答案 0 :(得分:0)

如果要隐藏所有段(而不仅仅是最后一段),则需要保留对所有段的引用。您还需要使PathStyle变量不是创建该行的函数的本地变量。