Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

前端 未结 11 659
傲寒
傲寒 2020-12-02 04:32

Given a database of places with Latitude + Longitude locations, such as 40.8120390, -73.4889650, how would I find all locations within a given distance of a specific locatio

11条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 05:16

    Thanks to the solution provided by @yogihosting I was able to achieve similar result from schemaless columns of mysql with codes shown below:

    // @params - will be bound to named query parameters
    $criteria = [];
    $criteria['latitude'] = '9.0285183';
    $criteria['longitude'] = '7.4869546';
    $criteria['distance'] = 500;
    $criteria['skill'] = 'software developer';
    
    // Get doctrine connection 
    $conn = $this->getEntityManager()->getConnection();
    
            $sql = '
                   SELECT DISTINCT m.uuid AS phone, (((acos(sin((:latitude*pi()/180)) * sin((JSON_EXTRACT(m.location, "$.latitude")*pi()/180))+cos((:latitude*pi()/180)) * 
                  cos((JSON_EXTRACT(m.location, "$.latitude")*pi()/180)) * 
                  cos(((:longitude - JSON_EXTRACT(m.location, "$.longitude"))*pi()/180))))*180/pi())*60*1.1515*1.609344) AS distance FROM member_profile AS m 
                   INNER JOIN member_card_subscription mcs ON mcs.primary_identity = m.uuid
                   WHERE mcs.end > now() AND JSON_SEARCH(m.skill_logic, "one", :skill) IS NOT NULL  AND (((acos(sin((:latitude*pi()/180)) * sin((JSON_EXTRACT(m.location, "$.latitude")*pi()/180))+cos((:latitude*pi()/180)) * 
                  cos((JSON_EXTRACT(m.location, "$.latitude")*pi()/180)) * 
                  cos(((:longitude - JSON_EXTRACT(m.location, "$.longitude"))*pi()/180))))*180/pi())*60*1.1515*1.609344) <= :distance ORDER BY distance
                   ';
            $stmt = $conn->prepare($sql);
            $stmt->execute(['latitude'=>$criteria['latitude'], 'longitude'=>$criteria['longitude'], 'skill'=>$criteria['skill'], 'distance'=>$criteria['distance']]);
            var_dump($stmt->fetchAll());
    

    Please note the above code snippet is using doctrine DB connection and PHP

提交回复
热议问题