how to select zip codes in specific area/range? - php

I have a customer that requires that a user can add his/her zip code, then an administrator can select users in specific area range
for example:
user - zip code
1 - 24533
2 - 56924
3 - 35993
4 - 13435
admin's zip code is 39824
He needs to select people in area range of 5 kilometers by zipcode.
How can this happen using php or any other solutions?

Very simple
You just need the latitude and longitude of the zipcodes against which zipcode you want to get the zipcodes. If you not have longitude and latotude get it from google it is free. you can easily get latitude and longitude by zipcode.
For example you want to get the zipcodes round 100 mile of 'H8t'
i have a table of zipcodes having latitude and longitude info.
First i write a query to my table to get latitude and longitude
SELECT * FROM Tbl_Master_ZIPCodes WHERE ZIPcode ='H8T'
after getting latitude and longitude i write a query below to get all zipcodes in the range of 100 miles of 'H8T'
SELECT distinct zipcode,
3963 * (ACOS((SIN(45.456700/57.2958) * SIN(latitude/57.2958)) + (COS(45.456700/57.2958) * COS(latitude/57.2958) * COS(longitude/57.2958 - -73.712000/57.2958)))) AS distance
FROM Tbl_Master_ZIPCodes
WHERE 3963 * (ACOS((SIN(45.456700/57.2958) * SIN(latitude/57.2958)) + (COS(45.456700/57.2958) * COS(latitude/57.2958) * COS(longitude/57.2958 - -73.712000/57.2958)))) <= 100 Order by Distance

php/mysql zip code proximity search
But, personally, I like the zip code range and distance calculation solution for you. If you had lat and long I would suggestion another but this seems to be similar to what you need.
http://www.micahcarrick.com/php-zip-code-range-and-distance-calculation.html

If you are receiving address with the zip code, then you can query the Google geocode Api to get the geocode of these addresses.
Once you have these geocodes, calculating distance can be done using code sample from this site

Related

Querying a DB for locations in an area

I'm interested in making a site which will store several locations and needs to be able to find them based on a user's query. Similar to how sites like Yelp, Zomato, Zillow, etc. function. My preferred tech stack is PHP/MySQL.
That said, I have a few related questions. Given a database of locations with their associate latitude/longitude coordinates...
How are they able to query their database of locations and return the ones within X distance of a specific city or ZIP code?
Furthermore, how can they query their database for locations that, instead of being within proximity, are within very specific city or state limits? Where do they get their boundary data from and how do you determine if a coordinate falls within that boundary in an efficient manner?
Lastly, I notice that some of the sites have city-specific links on their site. I would have expected city data to be pulled from remote mapping APIs, but they often associate images and other content with those cities. Do these sites store the names of all cities in their own database? Where do they get their list?
This will help with your first point.
I use this query to search properties in my database by distance from a starting point. The starting point is the longitude and latitude, $coordX and $coordY. I get these from doing a geocode lookup on the Google Maps API:
SELECT properties.*,
(
( ACOS(SIN(".$coordX." * PI() / 180) *
SIN(coordX * PI() / 180) + COS(".$coordX." * PI() / 180) *
COS(coordX * PI() / 180) * COS((".$coordY." - coordY) *
PI() / 180)) * 180 / PI()) * 60 * 1.1515
)
AS distance
FROM properties
order by distance
In my table I store the coordinates of the coordinates of individual properties in the coordX and coordY columns.
Here's MySQL function that will take two latitude/longitude pairs, and give you the distance in degrees between the two points.
It uses the Haversine formula to calculate the distance. Since the Earth is not a perfect sphere, there is some error near the
poles and the equator.
To convert to miles, multiply by 3961.
To convert to kilometers, multiply by 6373.
To convert to meters, multiply by 6373000.
To convert to feet, multiply by (3961 * 5280) 20914080.
DELIMITER $$
CREATE FUNCTION haversine(
lat1 FLOAT, lon1 FLOAT,
lat2 FLOAT, lon2 FLOAT
) RETURNS float
NO SQL
DETERMINISTIC
COMMENT 'Returns the distance in degrees on the Earth between two known points of latitude and longitude. To get miles, multiply by 3961, and km by 6373'
BEGIN
RETURN DEGREES(ACOS(
COS(RADIANS(lat1)) *
COS(RADIANS(lat2)) *
COS(RADIANS(lon2) - RADIANS(lon1)) +
SIN(RADIANS(lat1)) * SIN(RADIANS(lat2))
));
END;
DELIMITER ;
Add columns to your address table for latitude and longitude with a type of FLOAT(10,6).
Write a php script to do the lookup of the lat/long when the record is saved.
Then you can do a select against the table to get a list of addresses with distances. You can even sort
the results by distance, or limit the result to a certain radius from the reference location.
SELECT
`street`,
`city`,
`state`,
`zip`,
(haversine($ref_location_lat,$ref_location_long,`lat`,`long) * 3961) as `distance`
FROM `address_table`
WHERE (haversine($ref_location_lat,$ref_location_long,`lat`,`long) * 3961) < 300 // Example for limiting returned records to a raduis of 300 miles.
ORDER BY haversine($ref_location_lat,$ref_location_long,`lat`,`long) DESC; // Don't need actual distance for sorting, just relative distance.

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

Searching record within latitude and longitude range

hi i am using this map
https://google-developers.appspot.com/maps/articles/mvcfun/step6
i can get the latitude and longitude of the required location also i can get the distance (radius). so i have a database in which my each record have latitude and longitude. i want to search the record within the range selected on the map. how the sql query will work ?
for better explanation my each record have a latitude and longitude. user will select the map and i want to search the record within selected range.
The way I have always done this is to use the maps api to draw a circle with the required radius, find the lat long bounds of this circle and then query the database:
SELECT * FROM yourtable WHERE lat BETWEEN a AND c AND lng between b AND d
Where a and b are you top left coordinates and c and d are your bottom right. (more information available here).
Now that you have all objects within your bounding box you will need to pass them back to your front-end and determine whether or not they are within your radius. See this answer for more information.

Select locations based on distance between geocodes using SQL query

I have an SQL database containing hotel information, some of which is the geocoded lat/lng generated by Googles geocoder.
I want to be able to select (directly using an SQL query) all the hotels within a certain range. This range will never be more than 50km so I dont need to go as detailed as alot of answers on here are suggesting (taking into account earth curvature and the fact its not a perfect sphere isnt an issue over the distances im searching).
Im thinking a simple Pythagorian formula would suffice, but I dont know what the latitude and longitude figures represent (and therefore how to convert to metres) and also ive read on a couple of 'simple' solutions to my problem that there are issues with their formulas and calculating distances between two locations either side of the meridian line (as I am based in London this will be a big issue for me!!)
Any help would be great, thankyou!
----Helpful Information-----
My database stores the geocoded data in the following format:
geo_lat: 51.5033630,
geo_lon; -0.1276250
This is a select clause that will get your distance into kilometers. From there you can use a where clause to filter it down to less than 25 kilometers or whatever you want. If you want it in miles just take off the * 1.609344 conversion.
$latitude = [current_latitude];
$longitude = [current_longitude];
SELECT
((((acos(sin((".$latitude."*pi()/180)) * sin((`geo_lat`*pi()/180))+cos((".$latitude."*pi()/180)) * cos((`geo_lat`*pi()/180)) * cos(((".$longitude."- `geo_lon`)* pi()/180))))*180/pi())*60*1.1515) * 1.609344) as distance
FROM
[table_name]
WHERE distance
You can use a simple map projection and straight distances for example equirectangular projection. In the formula on this website you can also use a simplier formula without the square root:http://www.movable-type.co.uk/scripts/latlong.html. Of course you can use a bounding box to filter the query:How to calculate the bounding box for a given lat/lng location?, https://gis.stackexchange.com/questions/19760/how-do-i-calculate-the-bounding-box-for-given-a-distance-and-latitude-longitude.

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

Categories