使用getZoom隐藏标记的选项不起作用

时间:2018-02-18 16:20:21

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

有没有人可以帮助我理解为什么使用getZoom隐藏标记的选项在我的脚本中不起作用?

我已经通过添加另一个有效且似乎更简单的解决方案更新了代码

部分代码:

google.maps.event.addListener(map, 'zoom_changed', function() {
    var zoom = map.getZoom();
    for (i = 0; i < locations.length; i++) {
        markers[i].setVisible(zoom >= 10);
    }
});

所有代码:

&#13;
&#13;
function round_down(n) {
    if (n > 0) {
      return Math.ceil(n / 0.05) * 0.05;
    } else {
      return 0;
    }
  }

var map;
var pointCount = 0;
var locations = [];
var markers = [];
var gridWidth = 3660; // hex tile size in meters
var bounds;

var places = [
  [55.3, 14.8],
  [55.25, 14.85],
]

var SQRT3 = 1.73205080756887729352744634150587236;

$(document).ready(function(){
  
  bounds = new google.maps.LatLngBounds();
  
  map = new google.maps.Map(document.getElementById("map_canvas"), {center: {lat: 55.3, lng: 14.8}, zoom: 11});
  
  // Adding a marker just so we can visualize where the actual data points are.
  // In the end, we want to see the hex tile that contain them
  places.forEach(function(place, p){
    
    latlng = new google.maps.LatLng({lat: place[0], lng: place[1]});
    marker = new google.maps.Marker({
		position: latlng, 
		map: map})
		markers.push(marker);
		marker.addListener('click', set_window);
    google.maps.event.addListener(map, 'zoom_changed', function() {
    var zoom = map.getZoom();
    for (i = 0; i < locations.length; i++) {
        markers[i].setVisible(zoom >= 10);
    }
});
    // Fitting to bounds so the map is zoomed to the right place
    bounds.extend(latlng);
  });
  
  
  
  // Now, we draw our hexagons! (or try to)
  locations = makeBins(places);
  
  locations.forEach(function(place, p){
    drawHorizontalHexagon(map, place, gridWidth);
  })
    
    
});

  
  function drawHorizontalHexagon(map, position, radius){
    var coordinates = [];
    for(var angle= 0;angle < 360; angle+=60) {
       coordinates.push(google.maps.geometry.spherical.computeOffset(position, radius, angle));    
    }

    // Construct the polygon.
    var polygon = new google.maps.Polygon({
        paths: coordinates,
        position: position,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35,
        geodesic: true
    });
    polygon.setMap(map);
    polygon.addListener('click', set_window);
}

// Below is my attempt at porting binner.py to Javascript.
// Source: https://github.com/coryfoo/hexbins/blob/master/hexbin/binner.py

function distance(x1, y1, x2, y2){
  console.log(x1, y1, x2, y2);
  result =  Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
  console.log("Distance: ", result);
  return
}

function nearestCenterPoint(value, scale){
    div = value / (scale/2);
    console.log("div", div);
    mod = value % (scale/2);
    console.log("mod", mod);
    
    if(div % 2 == 1){
      increment = 1;
    } else{
      increment = 0;
    }
    
    rounded = scale / 2 * (div + increment);
    
    if(div % 2 === 0){
      increment = 1;
    } else{
      increment = 0;
    }
    
    rounded_scaled = scale / 2 * (div + increment);
    
    result = [rounded, rounded_scaled]
    console.log("nearest centerpoint to", value, result);
    return result;
}

function makeBins(data){
  bins = [];
  
  data.forEach(function(place, p){
    x = place[0];
    y = place[1];
    
    console.log("Original location:", x, y);
    
    px_nearest = nearestCenterPoint(x, gridWidth);
    
    py_nearest = nearestCenterPoint(y, gridWidth * SQRT3);
    
    z1 = distance(x, y, px_nearest[0], py_nearest[0]);
    z2 = distance(x, y, px_nearest[1], py_nearest[1]);
    
    if(z1 > z2){
      bin = new google.maps.LatLng({lat: px_nearest[0], lng: py_nearest[0]});
       console.log("Final location:", px_nearest[0], py_nearest[0]);
    } else {
      bin = new google.maps.LatLng({lat: px_nearest[1], lng: py_nearest[1]});
       console.log("Final location:", px_nearest[1], py_nearest[1]);
    }
  
    bins.push(bin);
    
  })
  return bins;
}
function set_window(event) {
    // Set Parameters
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();
    var coord_slug = this.position.lat() + ', ' + (Math.round(this.position.lng() * 20) / 20);
alert(coord_slug);
}
&#13;
<html>

  <head>
    <script data-require="jquery@*" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script data-require="bootstrap@*" data-semver="3.3.6" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
  </head>

  <body>
    <div class="col-xs-12">
      <h1>Hex Grid</h1>
    </div>
    <div id="map_canvas" style="width:100%; height:80vh;">
    </div>
  </body>

</html>
&#13;
&#13;
&#13;

其他链接:The working part of the script in Plunger

1 个答案:

答案 0 :(得分:0)

您的代码存在两个问题:

  1. .visible没有(有文档记录且有用)google.maps.Marker属性。记录的更改其可见性的方法是使用.setVisibility方法。
  2. marker是一个全局变量,因此一旦修复了上述内容,它只适用于最后一个marker。需要使用var在函数内定义它。
  3. 固定代码:

    places.forEach(function(place, p) {
      var latlng = new google.maps.LatLng({
        lat: place[0],
        lng: place[1]
      });
      var marker = new google.maps.Marker({
        position: latlng,
        map: map
      });
      markers.push(marker);
      marker.addListener('click', set_window);
      google.maps.event.addListener(map, 'zoom_changed', function() {
        zoom = map.getZoom();
        if (zoom < 10) {
          marker.setVisible(false);
        } else {
          marker.setVisible(true);
        }
      });
      // Fitting to bounds so the map is zoomed to the right place
      bounds.extend(latlng);
    });
    

    proof of concept fiddle

    enter image description here

    代码段

    function round_down(n) {
      if (n > 0) {
        return Math.ceil(n / 0.05) * 0.05;
      } else {
        return 0;
      }
    }
    
    var map;
    var pointCount = 0;
    var locations = [];
    var markers = [];
    var gridWidth = 3660; // hex tile size in meters
    var bounds;
    
    var places = [
      [55.3, 14.8],
      [55.25, 14.85],
    ]
    
    var SQRT3 = 1.73205080756887729352744634150587236;
    
    $(document).ready(function() {
    
      bounds = new google.maps.LatLngBounds();
    
      map = new google.maps.Map(document.getElementById("map_canvas"), {
        center: {
          lat: 55.3,
          lng: 14.8
        },
        zoom: 11
      });
      google.maps.event.addListener(map, 'zoom_changed', function() {
        document.getElementById('zoom').innerHTML = map.getZoom();
      })
    
      // Adding a marker just so we can visualize where the actual data points are.
      // In the end, we want to see the hex tile that contain them
      places.forEach(function(place, p) {
    
        latlng = new google.maps.LatLng({
          lat: place[0],
          lng: place[1]
        });
        var marker = new google.maps.Marker({
          position: latlng,
          map: map
        })
        markers.push(marker);
        marker.addListener('click', set_window);
        google.maps.event.addListener(map, 'zoom_changed', function() {
          zoom = map.getZoom();
          if (zoom < 10) {
            marker.setVisible(false);
          } else {
            marker.setVisible(true);
          }
        });
        // Fitting to bounds so the map is zoomed to the right place
        bounds.extend(latlng);
      });
    
      // Now, we draw our hexagons! (or try to)
      locations = makeBins(places);
      locations.forEach(function(place, p) {
        drawHorizontalHexagon(map, place, gridWidth);
      })
    });
    
    function drawHorizontalHexagon(map, position, radius) {
      var coordinates = [];
      for (var angle = 0; angle < 360; angle += 60) {
        coordinates.push(google.maps.geometry.spherical.computeOffset(position, radius, angle));
      }
    
      // Construct the polygon.
      var polygon = new google.maps.Polygon({
        paths: coordinates,
        position: position,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35,
        geodesic: true
      });
      polygon.setMap(map);
      polygon.addListener('click', set_window);
    }
    
    // Below is my attempt at porting binner.py to Javascript.
    // Source: https://github.com/coryfoo/hexbins/blob/master/hexbin/binner.py
    
    function distance(x1, y1, x2, y2) {
      console.log(x1, y1, x2, y2);
      result = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
      console.log("Distance: ", result);
      return
    }
    
    function nearestCenterPoint(value, scale) {
      div = value / (scale / 2);
      console.log("div", div);
      mod = value % (scale / 2);
      console.log("mod", mod);
    
      if (div % 2 == 1) {
        increment = 1;
      } else {
        increment = 0;
      }
    
      rounded = scale / 2 * (div + increment);
    
      if (div % 2 === 0) {
        increment = 1;
      } else {
        increment = 0;
      }
    
      rounded_scaled = scale / 2 * (div + increment);
    
      result = [rounded, rounded_scaled]
      console.log("nearest centerpoint to", value, result);
      return result;
    }
    
    function makeBins(data) {
      bins = [];
    
      data.forEach(function(place, p) {
        x = place[0];
        y = place[1];
    
        console.log("Original location:", x, y);
    
        px_nearest = nearestCenterPoint(x, gridWidth);
    
        py_nearest = nearestCenterPoint(y, gridWidth * SQRT3);
    
        z1 = distance(x, y, px_nearest[0], py_nearest[0]);
        z2 = distance(x, y, px_nearest[1], py_nearest[1]);
    
        if (z1 > z2) {
          bin = new google.maps.LatLng({
            lat: px_nearest[0],
            lng: py_nearest[0]
          });
          console.log("Final location:", px_nearest[0], py_nearest[0]);
        } else {
          bin = new google.maps.LatLng({
            lat: px_nearest[1],
            lng: py_nearest[1]
          });
          console.log("Final location:", px_nearest[1], py_nearest[1]);
        }
    
        bins.push(bin);
    
      })
      return bins;
    }
    
    function set_window(event) {
      // Set Parameters
      var lat = event.latLng.lat();
      var lng = event.latLng.lng();
      var coord_slug = this.position.lat() + ', ' + (Math.round(this.position.lng() * 20) / 20);
      alert(coord_slug);
    }
    html,
    body {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px;
      background-color: white;
    }
    
    #map_canvas {
      height: 90%;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <div id="zoom"></div>
    <div id="map_canvas"></div>