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'];
Related
I have a code for downloading longitude and latitude coordinates from google maps, it was working before but now it's returning null value. Below is my code;
<?php
//Optaining Latitude and Longitude
$address = $title;
$url = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".urlencode($address)."&sensor=false");
$response = json_decode($url);
$latitudee = "";
$longitudee = "";
if ($response->status == 'OK') {
$latitudee = $response->results[0]->geometry->location->lat;
$longitudee = $response->results[0]->geometry->location->lng;
}
echo $latitudee;
?>
Google now requires you to include API key for calling geocode API. Change the 'url' variable as follows-
$url = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".urlencode($address)."&key=YOUR_API_KEY");
The sensor parameter is no longer required to pass as per google developer guide
https://developers.google.com/maps/documentation/geocoding/intro
If you don't have an API key, you can get it here-
https://developers.google.com/maps/documentation/javascript/get-api-key
Also don't forget to restrict your key once you have one.
Returned error message states what is the problem here:
Keyless access to Google Maps Platform is deprecated.
Please use an API key with all your API calls to avoid service interruption.
For further details please refer to http://g.co/dev/maps-no-account
After recent changes to google maps, you will need to create an account to use google maps API, this will generate an API key and you have to append it to URL that you use
"http://maps.google.com/maps/api/geocode/json?address=".urlencode($address)."&key=YOUR_API_KEY"
you must Formatted your address:
$formattedAddr = str_replace(' ','+',$address);
Send request and receive json data by address:
$geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=false');
$output = json_decode($geocodeFromAddr);
Get latitude and longitute from json data:
if ($output->status == 'OK') {
$data['latitude'] = $output->results[0]->geometry->location->lat;
$data['longitude'] = $output->results[0]->geometry->location->lng;
}
I was able to find where the problem was, Google changed the API url to the one below;
$url = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($add`enter code here`ress)."&key=YOUR_API_KEY");
Do you know some utility or a web site where I can give US city,state and radial distance in miles as input and it would return me all the cities within that radius?
Thanks!
Here is how I do it.
You can obtain a list of city, st, zip codes and their latitudes and longitudes.
(I can't recall off the top of my head where we got ours)
edit: http://geonames.usgs.gov/domestic/download_data.htm
like someone mentioned above would probably work.
Then you can write a method to calculate the min and max latitude and longitudes based on a radius, and query for all cities between those min and max. Then loop through and calculate the distance and remove any that are not in the radius
double latitude1 = Double.parseDouble(zipCodes.getLatitude().toString());
double longitude1 = Double.parseDouble(zipCodes.getLongitude().toString());
//Upper reaches of possible boundaries
double upperLatBound = latitude1 + Double.parseDouble(distance)/40.0;
double lowerLatBound = latitude1 - Double.parseDouble(distance)/40.0;
double upperLongBound = longitude1 + Double.parseDouble(distance)/40.0;
double lowerLongBound = longitude1 - Double.parseDouble(distance)/40.0;
//pull back possible matches
SimpleCriteria zipCriteria = new SimpleCriteria();
zipCriteria.isBetween(ZipCodesPeer.LONGITUDE, lowerLongBound, upperLongBound);
zipCriteria.isBetween(ZipCodesPeer.LATITUDE, lowerLatBound, upperLatBound);
List zipList = ZipCodesPeer.doSelect(zipCriteria);
ArrayList acceptList = new ArrayList();
if(zipList != null)
{
for(int i = 0; i < zipList.size(); i++)
{
ZipCodes tempZip = (ZipCodes)zipList.get(i);
double tempLat = new Double(tempZip.getLatitude().toString()).doubleValue();
double tempLon = new Double(tempZip.getLongitude().toString()).doubleValue();
double d = 3963.0 * Math.acos(Math.sin(latitude1 * Math.PI/180) * Math.sin(tempLat * Math.PI/180) + Math.cos(latitude1 * Math.PI/180) * Math.cos(tempLat * Math.PI/180) * Math.cos(tempLon*Math.PI/180 -longitude1 * Math.PI/180));
if(d < Double.parseDouble(distance))
{
acceptList.add(((ZipCodes)zipList.get(i)).getZipCd());
}
}
}
There's an excerpt of my code, hopefully you can see what's happening. I start out with one ZipCodes( a table in my DB), then I pull back possible matches, and finally I weed out those who are not in the radius.
Oracle, PostGIS, mysql with GIS extensions, sqlite with GIS extensions all support this kind of queries.
If you don't have the dataset look at:
http://www.geonames.org/
Take a look at this web service advertised on xmethods.net. It requires a subscription to actually use, but claims to do what you need.
The advertised method in question's description:
GetPlacesWithin Returns a list of geo
places within a specified distance
from a given place. Parameters: place
- place name (65 char max), state - 2 letter state code (not required for
zip codes), distance - distance in
miles, placeTypeToFind - type of place
to look for: ZipCode or City
(including any villages, towns, etc).
http://xmethods.net/ve2/ViewListing.po?key=uuid:5428B3DD-C7C6-E1A8-87D6-461729AF02C0
You can obtain a pretty good database of geolocated cities/placenames from http://geonames.usgs.gov - find an appropriate database dump, import it into your DB, and performing the kind of query your need is pretty straightforward, particularly if your DBMS supports some kind of spatial queries (e.g. like Oracle Spatial, MySQL Spatial Extensions, PostGIS or SQLServer 2008)
See also: how to do location based search
I do not have a website, but we have implemented this both in Oracle as a database function and in SAS as a statistics macro. It only requires a database with all cities and their lat and long.
Maybe this can help. The project is configured in kilometers though. You can modify these in CityDAO.java
public List<City> findCityInRange(GeoPoint geoPoint, double distance) {
List<City> cities = new ArrayList<City>();
QueryBuilder queryBuilder = geoDistanceQuery("geoPoint")
.point(geoPoint.getLat(), geoPoint.getLon())
//.distance(distance, DistanceUnit.KILOMETERS) original
.distance(distance, DistanceUnit.MILES)
.optimizeBbox("memory")
.geoDistance(GeoDistance.ARC);
SearchRequestBuilder builder = esClient.getClient()
.prepareSearch(INDEX)
.setTypes("city")
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setScroll(new TimeValue(60000))
.setSize(100).setExplain(true)
.setPostFilter(queryBuilder)
.addSort(SortBuilders.geoDistanceSort("geoPoint")
.order(SortOrder.ASC)
.point(geoPoint.getLat(), geoPoint.getLon())
//.unit(DistanceUnit.KILOMETERS)); Original
.unit(DistanceUnit.MILES));
SearchResponse response = builder
.execute()
.actionGet();
SearchHit[] hits = response.getHits().getHits();
scroll:
while (true) {
for (SearchHit hit : hits) {
Map<String, Object> result = hit.getSource();
cities.add(mapper.convertValue(result, City.class));
}
response = esClient.getClient().prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
if (response.getHits().getHits().length == 0) {
break scroll;
}
}
return cities;
}
The "LocationFinder\src\main\resources\json\cities.json" file contains all cities from Belgium. You can delete or create entries if you want too. As long as you don't change the names and/or structure, no code changes are required.
Make sure to read the README https://github.com/GlennVanSchil/LocationFinder
I was wondering if anyone is aware of any PHP scripts which maps a UK City onto a Post Code.
I have found something like this:
case'North West England, England': {
$postcode = 'M1 2NQ';
break;
}
case'North East England, England': {
$postcode = 'NE1 6AD';
break;
}
case'South West England, England': {
$postcode = 'EX1 3AX';
break;
}
But it only covers areas as you can see, rather than cities such as 'Manchester, Edinburgh' etc.
Any input would be greatly appreciated.
Thanks,
AP
You might think of using Google Map API
You can use the ONS Postcode Directory (ONSPD). You'd have to set up a database and import all the data, then build your application round it.
I am trying to use http://www.hostip.info/use.html in my web app to show the approximate City location of an IP address. I cannot figure out how to actually show the contents of the API... Here is what I have that is not working.
function showCity($currIP){
$lookupData = 'http://api.hostip.info/get_html.php?ip='.$currIP;
return $lookupData;
}
Your API returns this:
Country: UNITED STATES (US)
City: Seattle, WA
IP: 168.111.127.225
So you need to do some string parsing on that result. Using the below will get your started:
$array = preg_split('/$\R?^:/m', $lookupData);
print_r($array);
Try this instead:
$array = preg_split("/[\r\n]/", $lookupData, -1, PREG_SPLIT_NO_EMPTY);
Also, as was mentioned by mcmajkel, if you use the JSON api link, you can get to it with this:
$lookupData = 'http://api.hostip.info/get_json.php?ip='.$currIP;
$api = json_decode($lookupData);
$myName = $api->country_name;
$myCode = $api->country_code;
$myCity = $api->city;
$myIP = $api->ip;
This call returns string, as mentioned by GregP. But you can call
http://api.hostip.info/get_json.php?ip=12.215.42.19
And get a nice piece of JSON in return, which will be easier to
parse
I want to parse this URL with PHP to get the latitude of a specific address (2+bis+avenue+Foch75116+Paris+FR):
I use the google maps web service: http://maps.googleapis.com/maps/api/geocode/json?address=2+bis+avenue+Foch75116+Paris+FR&sensor=false
// Get the JSON
$url='http://maps.googleapis.com/maps/api/geocode/json?address=2+bis+avenue+Foch75116+Paris+FR&sensor=false';
$source = file_get_contents($url);
$obj = json_decode($source);
var_dump($obj);
It doesn't work. I have this error :
OVER_QUERY_LIMIT
So I searched on the web and I found that there is a limitation using google maps api (Min 1 sec between 2 queries and max 2500 queries per day)
Do you know any way to convert an adress to --> Latitude/Longitude ???
You are accessing results incorrectly.
// Get the JSON
$url='http://maps.googleapis.com/maps/api/geocode/json?address=2+bis+avenue+Foch75116+Paris+FR&sensor=false';
$source = file_get_contents($url);
$obj = json_decode($source);
$LATITUDE = $obj->results[0]->geometry->location->lat;
echo $LATITUDE;