从谷歌地图中删除GeoJson图层

Removing GeoJson Layers from Google Maps

本文关键字:GeoJson 图层 删除 谷歌地图      更新时间:2023-09-26

我正在尝试使用草皮.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]);
}} 

提前非常感谢,

我找到了一个解决方案,方法是采用新的平滑坐标,然后在新的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);
}}

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

  //Remove layer from map if it exists
  if (mapLayer != null) {
    mapLayer.setMap(null);
  }
  //create new layer
  mapLayer = new window.google.maps.Data({ map: googleMap });