getting distance between two points using google gps api with php

家住魔仙堡 提交于 2019-12-08 08:14:54

问题


I found this link on Stack Overflow Google Maps - How to get the distance between two point in metre? which shows the following solution in regards to finding a km distance given two different latitude and longitude values:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>

var p1 = new google.maps.LatLng(45.463688, 9.18814);
var p2 = new google.maps.LatLng(46.0438317, 9.75936230000002);

alert(calcDistance(p1, p2));

//calculates distance between two points in km's
function calcDistance(p1, p2){
    return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
   }

}

This is great and works however I am creating an app that pulls lat and long values from a database and compares each one to a constant lat and longitude value to determine if the users from which I am pulling from the db are within a certain range of a set lat and long.

I'm doing this in PHP but I want to pass the constant lat and long values along with the current lat and long values to the above JavaScript function, calculate the distance and then return the value to a PHP variable. In other words I want to call a JavaScript function in PHP and return the JavaScript value back to the PHP variable.

I'm seeing a lot of forums that state this is impossible then some say it is. Can anyone help me with this or suggest another approach? will I just have to do some old fashioned calculus within PHP and forget the Google API plugin?


回答1:


You can use below query if you have latitude and longitude value in your database.

SELECT a.*,
            3956 * 2 * ASIN(SQRT( POWER(SIN(($lat - lat) * pi()/180 / 2), 2) + COS($lat * pi()/180) * COS(lat * pi()/180) *
            POWER(SIN(($long - longi) * pi()/180 / 2), 2) )) as
            distance FROM table
            GROUP BY id HAVING distance <= 500 ORDER by distance ASC

$lat and $long variable is the current position of user. lat and longi is the latitude and longitudle of entries.

Also refer to "Creating a Store Locator with PHP, MySQL & Google Maps" to understand how above query will work



来源:https://stackoverflow.com/questions/14995887/getting-distance-between-two-points-using-google-gps-api-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!