简体   繁体   中英

Google Maps API with PHP to find distance between two locations

On my current project, which is a delivery system, I have a list of available delivery drivers, which is shown on an orders page. But what I need is to show the distance each delivery is from the customers address. The distance should be shown next to each driver's name. Anyone have any clues on how I would go about this?

Assuming that you want driving distance and not straight line distance, you can use the Directions web service: You need to make an http or https request from your PHP script and the parse the JSON or XML response.

Documentation: https://developers.google.com/maps/documentation/directions/

For example: Boston,MA to Concord,MA via Charlestown,MA and Lexington,MA (JSON) http://maps.googleapis.com/maps/api/directions/json?origin=Boston,MA&destination=Concord,MA&waypoints=Charlestown,MA|Lexington,MA&sensor=false

Boston,MA to Concord,MA via Charlestown,MA and Lexington,MA (XML) http://maps.googleapis.com/maps/api/directions/xml?origin=Boston,MA&destination=Concord,MA&waypoints=Charlestown,MA|Lexington,MA&sensor=false

Note that there are usage limits.

You can easily calculates the distance between two address using Google Maps API and PHP.

$addressFrom = 'Insert from address';
$addressTo = 'Insert to address';
$distance = getDistance($addressFrom, $addressTo, "K");
echo $distance;

You can get the getDistance() function codes from here - http://www.codexworld.com/distance-between-two-addresses-google-maps-api-php/

this will out seconds between 2 location

$origin =urlencode('Optus Sydney International Airport, Airport Drive, Mascot NSW 2020, Australia');
$destination = urlencode('Sydney NSW, Australia');
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=$origin&destinations=$destination&key=your_key";
$data = @file_get_contents($url);
$data = json_decode($data,true);
echo $data['rows'][0]['elements'][0]['duration']['value'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM