Calculate the center point of multiple latitude/longitude coordinate pairs

后端 未结 21 1516
暖寄归人
暖寄归人 2020-11-27 09:27

Given a set of latitude and longitude points, how can I calculate the latitude and longitude of the center point of that set (aka a point that would center a view on all poi

21条回答
  •  無奈伤痛
    2020-11-27 09:38

    In Django this is trivial (and actually works, I had issues with a number of the solutions not correctly returning negatives for latitude).

    For instance, let's say you are using django-geopostcodes (of which I am the author).

    from django.contrib.gis.geos import MultiPoint
    from django.contrib.gis.db.models.functions import Distance
    from django_geopostcodes.models import Locality
    
    qs = Locality.objects.anything_icontains('New York')
    points = [locality.point for locality in qs]
    multipoint = MultiPoint(*points)
    point = multipoint.centroid
    

    point is a Django Point instance that can then be used to do things such as retrieve all objects that are within 10km of that centre point;

    Locality.objects.filter(point__distance_lte=(point, D(km=10)))\
        .annotate(distance=Distance('point', point))\
        .order_by('distance')
    

    Changing this to raw Python is trivial;

    from django.contrib.gis.geos import Point, MultiPoint
    
    points = [
        Point((145.137075, -37.639981)),
        Point((144.137075, -39.639981)),
    ]
    multipoint = MultiPoint(*points)
    point = multipoint.centroid
    

    Under the hood Django is using GEOS - more details at https://docs.djangoproject.com/en/1.10/ref/contrib/gis/geos/

提交回复
热议问题