MySQL - Find points within radius from database

前端 未结 3 667
无人及你
无人及你 2020-12-10 07:45

I have a table which has a POINT column containing the latitude and longitude of various locations.

I then also have a users location from geo-location

相关标签:
3条回答
  • 2020-12-10 07:55

    The query below actually worked for me :

    $query = "SELECT *,
        ( 6371 * 
        acos( 
        cos( radians( ".$user_lat." ) ) * 
          cos( radians( lat ) ) * 
          cos( radians( lng ) - 
          radians( ".$user_lng." ) ) + 
            sin( radians( ".$user_lat." ) ) * 
              sin( radians( lat ) ) ) ) 
              AS distance FROM parkings 
              HAVING distance <= ".$radius." ORDER BY distance ASC";
    
      $stmt = $conn->execute($query);
    
      $rows = $stmt->fetchAll('assoc');
    

    where: $user_lat and $user_lng is browser's lat and lng, $radius = 10, table name is parkings

    0 讨论(0)
  • I'm currently working on a project where I'm calculating distances between multiple locations. I'm using the following query for selecting object_id's which are within a given radius.

    SELECT id, 
    ( 6371 * 
        ACOS( 
            COS( RADIANS( db_latitude ) ) * 
            COS( RADIANS( $user_latitude ) ) * 
            COS( RADIANS( $user_longitude ) - 
            RADIANS( db_longitude ) ) + 
            SIN( RADIANS( db_latitude ) ) * 
            SIN( RADIANS( $user_latitude) ) 
        ) 
    ) 
    AS distance FROM the_table HAVING distance <= $the_radius ORDER BY distance ASC"
    

    I can't explain the ACOS formula itself because I got it from research.

    db_latitude = database latitude field
    db_longitude = database longitude field
    $user_latitude = browser latitude coördinate
    $user_longitude = browser longitude coördinate
    $the_radius = the radius that you want to search in
    

    This is in kilometers.

    0 讨论(0)
  • 2020-12-10 07:57

    May be this help for you, https://ru.scribd.com/presentation/2569355/Geo-Distance-Search-with-MySQL

    For Django I use this

        dist = 20 #дистанция 20 км
        mylon = 51.5289156201 # долгота центра
        mylat = 46.0209384922 # широта 
        lon1 = mylon-dist/abs(math.cos(math.radians(mylat))*111.0) # 1 градус широты = 111 км
        lon2 = mylon+dist/abs(math.cos(math.radians(mylat))*111.0)
        lat1 = mylat-(dist/111.0)
        lat2 = mylat+(dist/111.0)
        profiles = UserProfile.objects.filter(lat__range=(lat1, lat2)).filter(lon__range=(lon1, lon2))
    

    It search all users in squar 20km.

    0 讨论(0)
提交回复
热议问题