Find center of multiple locations in Google Maps

前端 未结 4 726
面向向阳花
面向向阳花 2020-11-27 12:14

I have just copied the code on this question and applied my latitude and longitudes. However, the latitudes and longitudes will be dynamic, and the center of th

相关标签:
4条回答
  • 2020-11-27 12:35
    private LatLng computeCentroid(List<LatLng> points) {
    double latitude = 0;
    double longitude = 0;
    int n = points.size();
    
    for (LatLng point : points) {
        latitude += point.latitude;
        longitude += point.longitude;
    }
    
    return new LatLng(latitude/n, longitude/n);
    

    }

    0 讨论(0)
  • 2020-11-27 12:43

    This approach does not work because it will average the numbers and not get the "middle" of the numbers (lat/long). Think of it like this, you have 6 points in the US, one in CA and 5 on east coast spread north and south. The 5 on east coast weight the average to the right(east) on the map and your center point would be (East to West) around Georgia. If you wanted to avoid using getCenter you would want to find the highest and the lowest of east direction (lat +/- and long +/-) and find the middle of each direction once you had the extremes.

    0 讨论(0)
  • 2020-11-27 12:48

    First you can create a LatLngBounds object by including all the dynamically generated locations. Use the extend method to include the points. Then you can get the center of the bound using the getCenter method.

    UPDATE:

    Code:

    var bound = new google.maps.LatLngBounds();
    
    for (i = 0; i < locations.length; i++) {
      bound.extend( new google.maps.LatLng(locations[i][2], locations[i][3]) );
    
      // OTHER CODE
    }
    
    console.log( bound.getCenter() );
    

    Illustration:

    enter image description here

    0 讨论(0)
  • 2020-11-27 12:48

    I'm doing this by averaging the latitudes and averaging the longitudes and using those averages as my center.

    Example:

    self.adjustPosition = function () {
        var lat = 0, lng = 0;
    
        if (self.nearbyPlaces().length == 0) {
            return false;
        }
    
        for (var i = 0; i < self.nearbyPlaces().length; i++) {
            lat += self.nearbyPlaces()[i].latitude;
            lng += self.nearbyPlaces()[i].longitude;
        }
    
        lat = lat / self.nearbyPlaces().length;
        lng = lng / self.nearbyPlaces().length;
    
        self.map.setCenter(new window.google.maps.LatLng(lat, lng));
    };
    
    0 讨论(0)
提交回复
热议问题