Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6814953
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T20:44:58+00:00 2026-05-26T20:44:58+00:00

I’ve recently started looking at the Google Maps API to try out something new

  • 0

I’ve recently started looking at the Google Maps API to try out something new in my websites. I am currently using this code:

<?php

$postcode = $_REQUEST['postcode'];

$url = 'http://maps.googleapis.com/maps/api/geocode/xml?address='.$postcode.'&sensor=false';
$parsedXML = simplexml_load_file($url);

if($parsedXML->status != "OK") {
echo "There has been a problem: " . $parsedXML->status;
}

$myAddress = array();
foreach($parsedXML->result->address_component as $component) {
if(is_array($component->type)) $type = (string)$component->type[0];
else $type = (string)$component->type;

$myAddress[$type] = (string)$component->long_name;
}
header('Content-Type: application/json');
echo json_encode($myAddress);


?>

which simply uses a postcode that I define and searches the Google database and then returns the town, county etc.

If possible, I would like to not only show the nearest town but also any within a 5-10 mile radius. Could someone tell me how I would go about doing this please?

Thanks for any help

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T20:44:59+00:00Added an answer on May 26, 2026 at 8:44 pm

    Update: I wrote up a more detailed blogpost about this specific subject on http://www.mullie.eu/geographic-searches/

    —

    Loop through all available towns using the Google Maps API to fetch their latitude & longitude. Save these somewhere (database). – Beware, Google will not accept an enormous amount of calls, so throttle your calls.

    Then, when fetching a town, you can use code similar to the code below to grab the cities withing a certain range:

    public static function getNearby($lat, $lng, $type = 'cities', $limit = 50, $distance = 50, $unit = 'km')
    {
        // radius of earth; @note: the earth is not perfectly spherical, but this is considered the 'mean radius'
        if ($unit == 'km') $radius = 6371.009; // in kilometers
        elseif ($unit == 'mi') $radius = 3958.761; // in miles
    
        // latitude boundaries
        $maxLat = (float) $lat + rad2deg($distance / $radius);
        $minLat = (float) $lat - rad2deg($distance / $radius);
    
        // longitude boundaries (longitude gets smaller when latitude increases)
        $maxLng = (float) $lng + rad2deg($distance / $radius / cos(deg2rad((float) $lat)));
        $minLng = (float) $lng - rad2deg($distance / $radius / cos(deg2rad((float) $lat)));
    
        // get results ordered by distance (approx)
        $nearby = (array) FrontendDB::getDB()->retrieve('SELECT *
                                                        FROM table
                                                        WHERE lat > ? AND lat < ? AND lng > ? AND lng < ?
                                                        ORDER BY ABS(lat - ?) + ABS(lng - ?) ASC
                                                        LIMIT ?;',
                                                        array($minLat, $maxLat, $minLng, $maxLng, (float) $lat, (float) $lng, (int) $limit));
    
        return $nearby;
    }
    

    Notes about the above code:

    • Own database wrapper is used, so transform to mysql_query, PDO, …
    • This will not be exact. We can’t do exact spherical calculations in the DB, so we’ve taken the upper & lower latitude & longitude limits. This basically means that a location which is slightly further than your distance (e.g. in the far north-east, just outside of the actual radius (which actually is pretty much a circle), but still inside the max latitude & longitude (because we compare it to square limits in the database). This will just give a rough but nut 100% accurate selection of cities withing your radius.

    I’ll try to illustrate this:

    _________________
    |      / \      |
    | Y  /     \    |
    |  /         \  |
    |(      X      )|
    |  \         /  |
    |    \     /    |
    |______\_/______|
    

    The above circle (somewhat) is the actual radius where you want to find locations within, based upon location X. This is too hard to accomplish straight out of your DB, so what we actually fetch from the DB is the surrounding square. As you can see, it’s possible that locations (like Y) fall within these max & min boundaries, though they aren’t actually withing the requested radius. These can later be filtered out through PHP though.

    To tackle this last issue, you could loop all results and calculate the exact distance between both your root location, and the close matches found, to calculate if they’re actually within your radius. For that, you could use this code:

    public static function getDistance($lat1, $lng1, $lat2, $lng2, $unit = 'km')
    {
        // radius of earth; @note: the earth is not perfectly spherical, but this is considered the 'mean radius'
        if ($unit == 'km') $radius = 6371.009; // in kilometers
        elseif ($unit == 'mi') $radius = 3958.761; // in miles
    
        // convert degrees to radians
        $lat1 = deg2rad((float) $lat1);
        $lng1 = deg2rad((float) $lng1);
        $lat2 = deg2rad((float) $lat2);
        $lng2 = deg2rad((float) $lng2);
    
        // great circle distance formula
        return $radius * acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($lng1 - $lng2));
    }
    

    This will calculate the (quasi) exact distance between location X and location Y, and then you can filter out exactly those cities that were near enough to pass the rough db-fetch, but not just near enough to actually be within your bounds.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm making a simple page using Google Maps API 3. My first. One marker
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a jquery bug and I've been looking for hours now, I can't
this is what i have right now Drawing an RSS feed into the php,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.