Google Maps Custom Tile Layer输入onclick将同一图层添加两次

时间:2018-11-28 21:21:43

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

我使用自定义输入控件在我的Google地图上添加了gebco磁贴。

它看起来工作正常,但我注意到该层被添加了两次。 我创建了一个sample fiddle,显示当您单击输入时,它将在控制台上两次添加gebco层。

如果效果更好,我还添加了一个代码段。因此我不知道为什么将图层添加两次。

有什么主意如何防止它两次添加gebco层?

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 2,
  maxZoom: 8,
  minZoom: 1,
  center: {
    lat: 0,
    lng: -0
  },
  disableDefaultUI: false,
  zoomControl: true,
  mapTypeControl: false,
  streetViewControl: false,
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

function CenterControl(controlDiv, map) {

  // Bulut Custom Map Control
  var controlUI = document.createElement('div');
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Please Select a Weather Layer';
  controlDiv.appendChild(controlUI);

  var controlText = document.createElement('div');
  controlText.innerHTML = '<table id="otherlayers"><tbody><tr><td><input type="checkbox" id="gebco" data-opacity="1"><label for="gebco">Wind Stream</label></td></tr></tbody></table>';
  controlUI.appendChild(controlText);

$("div").on("click", "#otherlayers input[id='gebco']", function (e) {        
        setgebcolayer(this);
    });

}

var gebcoLayer =
            new google.maps.ImageMapType(
                {
                    getTileUrl: function (coord, zoom) {
                        var tilesPerGlobe = 1 << zoom;
                        var x = coord.x % tilesPerGlobe;
                        if (x < 0) {
                            x = tilesPerGlobe + x;
                        }

                        var bbox2 = tileCoordsToBBox(map, coord, zoom, 256, 256);
                        var url = "https://www.gebco.net/data_and_products/gebco_web_services/web_map_service/mapserv?request=getmap&service=wms&BBOX=" + bbox2 + "&crs=EPSG:4326&format=image/png&layers=gebco_latest&width=256&height=256&version=1.3.0"
                        return url;
                    },
                    tileSize: new google.maps.Size(256, 256),
                    name: "Gebco",
                    isPng: true,
                    maxZoom: 18,
                    opacity: 0.3,
                });
                
                function setgebcolayer(control) {
        var checked = control.checked;
        if (checked == false) {
            var layername = "Gebco";
            for (_layer in map.overlayMapTypes.getArray()) {
                if (map.overlayMapTypes.getAt(_layer).name == layername) {
                    if (checked == false) {
                        map.overlayMapTypes.removeAt(_layer);
                        return;
                    }
                }
            }
        }
        map.overlayMapTypes.insertAt(0, gebcoLayer);
    }
                
                function tileCoordsToBBox(map, coord, zoom, tileWidth, tileHeight) {
    var proj = map.getProjection();
    var scale = Math.pow(2, zoom);
    var ne = proj.fromPointToLatLng(new google.maps.Point((coord.x + 1) * tileWidth / scale, coord.y * tileHeight / scale));
    var sw = proj.fromPointToLatLng(new google.maps.Point(coord.x * tileWidth / scale, (coord.y + 1) * tileHeight / scale));

    return [
        sw.lat(),
        sw.lng(),
        ne.lat(),
        ne.lng()
    ];
};

var centerControlDiv = document.createElement('div');
var centerControl = new CenterControl(centerControlDiv, map);

centerControlDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_LEFT].push(centerControlDiv);

        google.maps.event.addListener(map, "zoom_changed", function () {
            var z = map.getZoom();
            var layerArray = map.overlayMapTypes.getArray();
            console.log(layerArray);
        });
html,
body,
#map {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry"></script>
<div id="map"></div>

3 个答案:

答案 0 :(得分:2)

在使用输入复选框时,如下更好地选择监听change事件。可行!

 $(document).on("change","input[id='gebco']",function(e){

          setgebcolayer(this);

          var layerArray = map.overlayMapTypes.getArray();
          console.log(layerArray);

  })

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 2,
  maxZoom: 8,
  minZoom: 1,
  center: {
    lat: 0,
    lng: -0
  },
  disableDefaultUI: false,
  zoomControl: true,
  mapTypeControl: false,
  streetViewControl: false,
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

function CenterControl(controlDiv, map) {

  // Bulut Custom Map Control
  var controlUI = document.createElement('div');
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Please Select a Weather Layer';
  controlDiv.appendChild(controlUI);

  var controlText = document.createElement('div');
  controlText.innerHTML = '<table id="otherlayers"><tbody><tr><td><input type="checkbox" id="gebco" data-opacity="1"><label for="gebco">Wind Stream</label></td></tr></tbody></table>';
  controlUI.appendChild(controlText);

  $(document).on("change","input[id='gebco']",function(e){

      setgebcolayer(this);

      var layerArray = map.overlayMapTypes.getArray();
      console.log(layerArray);

  })

}

var gebcoLayer =
            new google.maps.ImageMapType(
                {
                    getTileUrl: function (coord, zoom) {
                        var tilesPerGlobe = 1 << zoom;
                        var x = coord.x % tilesPerGlobe;
                        if (x < 0) {
                            x = tilesPerGlobe + x;
                        }

                        var bbox2 = tileCoordsToBBox(map, coord, zoom, 256, 256);
                        var url = "https://www.gebco.net/data_and_products/gebco_web_services/web_map_service/mapserv?request=getmap&service=wms&BBOX=" + bbox2 + "&crs=EPSG:4326&format=image/png&layers=gebco_latest&width=256&height=256&version=1.3.0"
                        return url;
                    },
                    tileSize: new google.maps.Size(256, 256),
                    name: "Gebco",
                    isPng: true,
                    maxZoom: 18,
                    opacity: 0.3,
                });
                
                function setgebcolayer(control) {
        var checked = control.checked;
        if (checked == false) {
            var layername = "Gebco";
            for (_layer in map.overlayMapTypes.getArray()) {
                if (map.overlayMapTypes.getAt(_layer).name == layername) {
                    if (checked == false) {
                        map.overlayMapTypes.removeAt(_layer);
                        return;
                    }
                }
            }
        }
        map.overlayMapTypes.insertAt(0, gebcoLayer);
    }
                
                function tileCoordsToBBox(map, coord, zoom, tileWidth, tileHeight) {
    var proj = map.getProjection();
    var scale = Math.pow(2, zoom);
    var ne = proj.fromPointToLatLng(new google.maps.Point((coord.x + 1) * tileWidth / scale, coord.y * tileHeight / scale));
    var sw = proj.fromPointToLatLng(new google.maps.Point(coord.x * tileWidth / scale, (coord.y + 1) * tileHeight / scale));

    return [
        sw.lat(),
        sw.lng(),
        ne.lat(),
        ne.lng()
    ];
};

var centerControlDiv = document.createElement('div');
var centerControl = new CenterControl(centerControlDiv, map);

centerControlDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_LEFT].push(centerControlDiv);

        google.maps.event.addListener(map, "zoom_changed", function () {
            var z = map.getZoom();
            var layerArray = map.overlayMapTypes.getArray();
            console.log(layerArray);
        });
html,
body,
#map {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry"></script>
<div id="map"></div>

答案 1 :(得分:1)

JQuery运行click事件两次。点击以下行会触发两次:

$("div").on("click", "#otherlayers input[id='gebco']", function (e) {   

答案 2 :(得分:1)

这将解决您的问题:

$("div").on("click", "#otherlayers input[id='gebco']", function (e) {
        e.stopPropagation()
        setgebcolayer(this);
         var layerArray = map.overlayMapTypes.getArray();
            console.log(layerArray);
    });

您只需添加e.stopPropagation()

提琴:link