Skip to content Skip to sidebar Skip to footer

Google Maps Marker Only In A Specific Area

I have a map-canvas which covers the entire screen. #map-canvas { height: 100%; position: absolute; top: 0px; left: 0; right: 0; z-index: 0; } On top of this canvas th

Solution 1:

I presume you know map.fitBounds(bounds);

If you feed the markers as bounds, you will get your picture above. Now, imagine we have an extra point (an invisible marker) left on the map.

We will calculate where that point is supposed to be. we don't add it to the markers but we add it to bounds.

So I just wrote a function. You can choose the width of the sidebar. I set it to 0.5 (50% sidebar), see line 29. Adapt this to the value you need.

<style>#map {
  height: 400px;
}
</style><divid="map"></div><scriptsrc="https://maps.googleapis.com/maps/api/js?v=3.exp"></script><script>
  locations = [
    [50.86721032255901,4.317024205042674],
    [50.89585769377925,4.481363151385143],
    [50.834376046898974,4.298433814360454],
    [50.82280917273896,4.395368848158672]
  ];

  functioninitialize() {
    map = new google.maps.Map(document.getElementById("map"), {
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: new google.maps.LatLng(locations[0][0], locations[0][1]),
      zoom: 10
    });
    for (var i=0; i<locations.length; i++) {
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][0], locations[i][1]),
        map: map
      })
    }
    setBoundsLeftSidebar(locations, 0.5);
  }
  /**
  * @param mapFraction (float): 0.0 to 1.0 ; example: 0.6 means 40% of the map is covered by the sidebar, 60% by the map
  */functionsetBoundsLeftSidebar(points, mapFraction) {
    // first we want to know min and max longitudevar max = -180;
    var min = 180;
    // We make bounds.  The bounds are the markers + an extra point on the left (we will give it a latitude of point 0), see latervar bounds = new google.maps.LatLngBounds();
    for (var i=0; i<points.length; i++) {
      if(points[i][1] > max) {
        max = points[i][1];
      }
      if(points[i][1] < min) {
        min = points[i][1];
      }
      bounds.extend(new google.maps.LatLng(points[i][0], points[i][1]));
    }
    // So now we have min and max.  // we add a point to the left of minvar widthTotal = (max - min) / mapFraction;
    var pointExtremeLeft = max - widthTotal;
    bounds.extend(new google.maps.LatLng(points[0][0], pointExtremeLeft));
    map.fitBounds(bounds);
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>

Post a Comment for "Google Maps Marker Only In A Specific Area"