How can I search based on distance with the Google Maps API? - php

So here's the issue... I have a field where users can type in their address (which will be GeoCoded via Google Maps API).
I have several addresses of widgets in my database (saved as address.. again can easily be geocoded).
What I need is for the user to type in their address and for a list of my widgets to come up based on distance from their address. I have THOUSANDS of addresses for my widgets and users have an infinite number of addresses obviously.
Any ideas?
Thanks.

SELECT latitude, longitude, SQRT( POW( 69.1 * ( latitude - 52.58 ) , 2 ) +
POW( 69.1 * ( - 1.12 - longitude ) * COS( latitude / 57.3 ) , 2 ) ) AS distance
FROM location ORDER BY distance
Click Here
They provide several ways of calculating the distance - choose what works best for you.

If you are storing the items in a MySQL DB, then here's the basis what you need

You really CAN'T use google to calculate your geo distance filtering. To do that, you would have to send them YOUR data, have them store it, and query it for you. They may offer that service, now, or in the future, but I haven't heard of it.
In order of more legal, more capable, more expensive:
A/ As SINGLE points or locations of interest are input by customers of your site, collect the geo coordiniates. Then use your own search engine and search by distance from a point. MAY be a violation of the agreement with google, but they do mention 'caching' results to take the load off their servers. (The reason is my personal guess.)
B/ Use google to do bulk geocoding, perhaps ONE AT A TIME, to a max of 5000 per day per your site's IP Address last I saw. Not even sure if that is not a violation of the use agreement.
C/ Purchase a contract with a geocoding service, and store what they geocode for you.
D/ Purchase a geocoding library and do your own geocoding.

This blog post, "Calculate Distance using Google Maps API", may be of some assistance.

Related

MySQL Calculate Geolocation Distance with variable radiuses

I'm building a geolocation advertising platform and I've run into a snag. I can successfully calculate all of the businesses advertising within a given radius to a user using this (page 8). Now, the client wants to change the radiuses of the advertisers which you can think of as "service areas". A basic advertiser will have a service radius of 100 miles, but other companies who are larger or spend more on advertising might have a service area of 250 or 500 miles, for example. With this change, the previous calculation does not work.
How can I take all of these variable radiuses and distances in order to return all of the advertisers that would be valid for a visitor?
To better illustrate my problem, take a look at:
Currently we calculate and return all of the advertisers within a 100 mile radius of a user (companies A, B, and C). With the new change, we need to return all of the companies that have a service area that covers the user, which includes company D. Company E has a smaller service area/radius which doesn't cover the user, so that record should not be returned.
The advertiser's table currently looks similar to:
id
name
lat
lng
radius
Given lat/lng of two points distance in miles can be calculated, see:
Find distance between two points using latitude and longitude in mysql
So if the visitor position is given (let's define it as visitor_latitude and visitor_longitude) the query that returns all the advertisers in range is:
SELECT *,
69.0412 * DEGREES(ACOS(COS(RADIANS(lat))
* COS(RADIANS(visitor_latitude))
* COS(RADIANS(lng - visitor_longitude))
+ SIN(RADIANS(lat))
* SIN(RADIANS(visitor_latitude)))) AS distance
FROM advertisers
WHERE distance <= radius

Get offers nearby longitude and latitude?

I currently have the users longitude and latitude and will show rows in my database from other offers where the radius is 150 meter example.
How can i make this? Each offer has latitude and longitude also.
I am really confused if this can be possible.
Please some expert help me.
$o->prepare("offers",array(
"longtitude" => "10.2039494",
"latitude" => "55.203949",
"radius" => 150 //in meters
)
);
Prepare should make some kind of MySQL query that shows offers in the radius from the users latitude and longitude for 150 meter (or 2km, i should be available to change this?). Example (OFFERS IN DATABASE WITH LONG AND LATITUDE)
'55.395591', '10.385513'
'55.395554', '10.385208'
I am really stuck from here
Calculating a rough distance or more exact distance between two long / lat points (straight line distance that is) is pretty straight forward math and you can find a ton of examples by searching e.g.: http://www.movable-type.co.uk/scripts/latlong.html
Note this will not be routable (driving/walking) distance for which you must leverage something like Google Maps.

calculate distance

i am designing a recruitment database, and i need it to perform several tasks that all involve integrating a way of calculating distance:
1) calculate the distance the candidate lives from the client?
2) calculate the clients within a radius of the candidates available for work on any given day?
3) calculating the number of candidates with the correct qualifications for the vacancy within a radius of the client.
as you can see i need to calculate the distance in 2 main ways 1) radius 2) as the crow flies, i would prefer exact distance but the first will do.
i know that i can integrate Google maps or some other web based mapping but i want the system to be stand alone so it can function without an internet connection.
the system will have a HTML5 front end and the Back end is in Mysql and PHP.
thank you biagio
The distance between 2 points could be calculated with the following formula :
6371*acos(cos(LatitudeA)*cos(LatitudeB)*cos(longitudeB-longitudeA)+sin(LatitudeA)*sin(latitudeB))
Of course it's a "crow flies" approximation in Km.
Wich can be translated to php by :
$longA = 2.3458*(M_PI/180); // M_PI is a php constant
$latA = 48.8608*(M_PI/180);
$longB = 5.0356*(M_PI/180);
$latB = 47.3225*(M_PI/180);
$subBA = bcsub ($longB, $longA, 20);
$cosLatA = cos($latA);
$cosLatB = cos($latB);
$sinLatA = sin($latA);
$sinLatB = sin($latB);
$distance = 6371*acos($cosLatA*$cosLatB*cos($subBA)+$sinLatA*$sinLatB);
echo $distance ;
With that you could compute the distance between two points (people) and of course determine if a point is in a radius of an other.
Just a thought: If your clients and candidates live in a very limited area, I would use a rectangular map and enter x and y values for all cities in that area in a database.
Due to the pythagorean theorem, you can say:
distance² = (x-value client - x-value candidate)² + (y-value client - y-value candidate)²
First, isn't the radius actually the 'as crow flies' distance from the client to the candidates? Anyway...you will need to figure out an algorithm for computing what you need based on the distance between the points.
If you want the system to be stand-alone you will need to have the values for the coordinates (latitude, longitude) of the points. For this, you will probably need and internet connection and the use of a service like google maps to find the coordinates based on the addresses of the points. But once you store then in your db, you will not need an internet connection.
There is a formula for computing the distance between two points based on the coordinates, you will easily find it :)

Locate nearest major city

I'm working on a website that allows users to find our nearest Motel location (There are 26 of them across the US). I have a list of cities where they are located at.
I want to display the nearest location when a user goes on our front page. For example if a user comes from Newark, NJ, he will be shown images from our NYC motel and if a user comes from San Jose, CA he will be shown San Francisco images.
What's the best way to do this? Does anyone know any examples out there on the web that shows what I'm trying to do? Is this even possible?
I saw Groupon and LivingSocial using this so I thought why dont I give it a shot. :)
If you're using apache, you can give geoip a try.
http://www.maxmind.com/app/mod_geoip
You'd first need to store the latitude/longitude coordinates of your motels in a database - use google maps, it won't take too long with 26.
Then get the visitor location, using something like IP2Location - http://www.ip2location.com/developers.aspx
Then calculate the distance between the visitor and each of your motels - http://sebastian-bauer.ws/en/2010/12/12/geo-koordinaten-mysql-funktion-zur-berechnung-des-abstands.html (it is in English...)
You could give Geolite city a try. It is free (with an attribution clause) or can alternatively be bought. That reduces the "find closest city to user's IP address" problem to "find the closest city to a known city".
The same company offers a city database, which among other things contains longitude/latitude. That should do the trick.
You can get the nearest city to an IP address using the free data on MaxMind.com (I beleive you can pay for more accurate databases). If you can get the lat/long for the city and compare it to the lat/long for each of your motels you win :)
What you want is to store the lat/lng coordinates of the motels and then let the user type his location into the browser most likely a zipcode and then you want to use the harvesine formule to calc the distance between the user and the motel to display nearby motels. Or you can use a IP to geo coordinate service like IP2location to get the users location.
I used this code to calculate distance of a googlemaps latitude and longitude from a table of addresses.
Geocode was a function that returned an array of latitude and longitude from google maps api given an address string, in the case below a zip. The table of your locations would have to include lat and lng columns. In this example i used decimal(8,5) types but you could also use a point column type.
$starting_location = geocode($zip);
$distance = '(3959 * acos(cos(radians('.$starting_location['latitude'].')) * cos(radians(lat)) * cos(radians(lng) - radians('.$starting_location['longitude'].')) + sin(radians('.$starting_location['latitude'].')) * sin(radians(lat))))';
$location_row = query('SELECT location_id,addr,addr2,city,state,zip,phonenumber,'.$distance.' AS distance FROM location_info WHERE '.$distance.' is not null ORDER BY distance LIMIT 1');
Correct me if I am linking to another's answer incorrectly, but I think I got my direction from this question: Fastest Way to Find Distance Between Two Lat/Long Points

Display in range addresses within x miles of a geo location with google maps

In my database I have a list of places and for each I have a street name and number, postcode, city and county. Some of them have a latitude and longitude location.
And I have the geo location of the city centre for example. I would like to display only the places that are within X miles of the city centre on a google map.
Incase this would need a geo location for each of my places to work, I could perhaps set up a script to use google maps api to use geocoding to get a geo location for all my places and update the database with the lat/lng. Then I would have a database full of lat and long locations to work from.
Once all the places have a lat/lng then maybe mysql can return the within range addresses?
This is not hard once you have lat / long data, and if somebody gives you the great circle distance formula in mySQL format.
#maggie gave a good reference. How to efficiently find the closest locations nearby a given location
Indexing strategy: Keep in mind that one minute of latitude (1/60 degree) is one nautical mile, or 1.1515 statute miles (approximately) all over the world. So index your latitude column and do your search like this. (If you're in the part of the world that uses km, you can convert; sorry for the Old-British-Empire-Centric answer, but they did define the nautical mile.)
WHERE mylat BETWEEN column.lat-(myradius*1.1515) AND column.lat+(myradius*1.1515)
AND (the big distance formula) <= myradius
This will give you both decent data base indexing AND reasonably accurate distance circles.
One extra refinement: You can index longitude too. The trouble is that ground distance isn't directly related to longitude. At the equator it is one nautical mile per minute, but it gets smaller, and at the poles there are singularities. So, you can add another term to your WHERE. It gives correct results but isn't as selective as latitude indexing. But it still helps the indexing lookup, especially if you have lots of rows to sift through. So you get:
WHERE mylat BETWEEN column.lat-(myradius*1.1515) AND column.lat+(myradius*1.1515)
AND mylon BETWEEN column.lon-(myradius*1.1515) AND column.lon+(myradius*1.1515)
AND (the big distance formula) < myradius
Most likely you want to use a space-filling-curve or a spatial index to reduce your 2D problem to a 1D problem. For example you can combine the lat/long pair with a z-curve or a hilbert curve. I use for myself a hilbert curve to search for postcodes. You can find my solution at phpclasses.org ( hilbert-curve ).

Categories