从Google地图中删除GeoJson图层

时间:2016-02-11 09:09:19

标签: javascript google-maps geojson

我尝试使用turf.js库从Google地图中删除GeoJson图层数组,以平滑多边形线。

我可以创建图层并将它们添加到地图中,但是当我尝试删除图层时,我得到以下错误代码:

Uncaught TypeError: a.getId is not a function

要添加图层,我执行此操作,循环浏览我的GeoJson文件...

else if(Type==="LineString" && Pype==="isobar") {
//DO ISOBARS STUFF=================================
//GET LNG/LAT======================================
CorrLEN     = dataID1.features[i].geometry.coordinates.length;
var Corrds =[];
var Corrs =[];
var LNGLAT ={};
var CORRS  = new Object();
var  x=0;
for (x=0;x<CorrLEN;x++){
var  a = x-1;
LNGLAT = (dataID1.features[i].geometry.coordinates[x]); 
Corrds.push(LNGLAT);
}
//=================================================================
//GET COLOUR INFO===================================================
var STCL = dataID1.features[i].properties.strokeColor;
var STOP = dataID1.features[i].properties.strokeOpacity;
var STSW = dataID1.features[i].properties.strokeWeight;
//=================================================================
LL     = turf.linestring(Corrds);  
curved = turf.bezier(LL,20000, 0.35);  
curved.properties = {weight:STSW,color:STCL};
map.data.setStyle(function(feature) {
return {strokeWeight:feature.getProperty('weight'),
        strokeColor: feature.getProperty('color')
       };            
 });
IsoBars.push(curved);

然后我使用以下功能添加或删除图层

//SHOW ISOBARS (works fine)
function ShowIsoBars() {
for (var i = 0; i < IsoBars.length; i++) { 
map.data.addGeoJson(IsoBars[i]);
}} 

//HIDE ISOBARS (Gets the error) Uncaught TypeError: a.getId is not a function
function HideIsoBars() {
for (var i = 0; i < IsoBars.length; i++) { 
map.data.remove(IsoBars[i]);
}} 

非常感谢,

2 个答案:

答案 0 :(得分:1)

我找到了一个解决方案,采用新的平滑坐标,然后在新的google.maps.Polyline中使用它们

 var Path =[];
 var  x=0;
 for (x=0;x<CorrLEN;x++){
 Path.push(new google.maps.LatLng(curved.geometry.coordinates[x][1],curved.geometry.coordinates[x][0])); 
 } 
 var IsoBar = new google.maps.Polyline({
           path: Path,
           geodesic: true,
           strokeColor: STCL,
           strokeOpacity: STOP,
           strokeWeight: STSW
           });

 IsoBars.push(IsoBar);

然后我可以使用以下功能来显示或隐藏图层

function ShowIsoBars() {
for (var i = 0; i < IsoBars.length; i++) { 
IsoBars[i].setMap(map);
}}

function HideIsoBars() {
for (var i = 0; i < IsoBars.length; i++) { 
IsoBars[i].setMap(null);
}}

答案 1 :(得分:0)

我发现而不是从图层中删除所有对象。破坏并重新创建该图层更容易,从而避免了该错误:

  //Remove layer from map if it exists
  if (mapLayer != null) {

    mapLayer.setMap(null);
  }

  //create new layer
  mapLayer = new window.google.maps.Data({ map: googleMap });