Google Maps API & PHP+MySQL – working with radius and distance

I needed to find out how to work with Google Geo API in my last project and especially with calculating a radius and distance between two geo points. Another goal was to get a latitude and longtitude from the address typed in the register form (in the background). Finally it was quiet easy. Here is the solution:First of all I had to collect geo data from the registering users, so that I could store their latitude and longitude from their address typed into the register form. As long as I had more fields presenting an address I had to merge data to one single string and send them to Google GEO API, which sends me a response with complete address including latitude and longitude and much more data than I expected. But I will get to this response later. Now I will show You how I collect data from the register form and send them to Google GEO API.

Lets say, that I have following form:

<form action="#" method="post">
		<input id="googleCity" name="googleCity" type="hidden" />
		<input id="googleDistinct" name="googleDistinct" type="hidden" />
		<input id="googleCountry" name="googleCountry" type="hidden" />
		<input id="googleCompleteAddress" name="googleCompleteAddress" type="hidden" />
		<input id="googleLatitude" name="googleLatitude" type="hidden" />
		<input id="googleLongtitude" name="googleLongtitude" type="hidden" />
		<input id="googleStatus" name="googleStatus" type="hidden" />
<!-- Some other fields like name etc. -->
	<label for="street">
		<input id="street" name="street" type="text" />
	</label>
	<label for="city">
		<input id="city" name="city" type="text" />
	</label>
	<label for="zip">
		<input id="zip" name="zip" type="text" />
	</label>
<!-- Some other fields like email etc.-->
		<input type="submit" value="Register" />
</form>

Now I have to parse typed values by user into the javascript code, which will immidiately send this string into Google Maps API. This part of code is fit for a jQuery library and You have to also include Google Maps API with Your API key which can be genarated on Google Maps API Sign Up page.
Here is the basic code for loading all neccessary libraries:

<script type="text/javascript" src="http://www.google.com/jsapi?key=HereGoesYourGoogleMapsApiKeyGeneratedOnLinkAbove"></script>
            <script type="text/javascript" charset="utf-8">
                    google.load("maps", "2.x");
                    google.load("jquery", "1.4.2");
              </script>

Now I will type some code, which will handle typed strings into the form and send them to Google Maps API. Here is the code:

    $(document).ready(function(){
      var geo = new GClientGeocoder();
//live function checks all the time fields street, city and zip for their blur action, at this moment it tries to get Geo data from Google - in regular way it should take max. 3 calls to Google
            $("input#street,input#city,input#zip").live("blur", function(){
//here is being built a variable including data from all address fields
                var address = $('input#frmregisterUserForm-ulice').val() + ', '+ $('input#frmregisterUserForm-cisloPopisne').val() + ', ' + $('input#frmregisterUserForm-mesto').val();
//let`s send complete address to Google and try to request data from API
                geo.getLocations(address, function (result){
                    statusCode = result.Status.code;
                    if (statusCode && statusCode == '200') {
//status code 200 means, that response is OK and Google found the place I was looking for and it returns me all data I want - so I will store them into hidden fields inside form defined above
                        $("input#googleDistinct").val( result.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName );
                        $("input#googleCity").val( result.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.LocalityName );
                        $("input#googleCountry").val( result.Placemark[0].AddressDetails.Country.CountryName );
                        $("input#googleCompleteAddress").val( result.Placemark[0].address );
                        $("input#googleLongitude").val( geocode[0] );
                        $("input#googleLatitude").val( geocode[1] );
                        $("input#googleStatus").val( result.Status.code );
                    } else {
                        $("input#frmregisterUserForm-googleStatus").val( result.Status.code );
                    }
                });
            });
    });

As You can see, if You will provide to google just the partial address, Google Maps API will return to You complete address incl. distinct, country and much more information about this location incl. coordinates of that place – what we wanted the most.

_xdc_._0g7bwexyl && _xdc_._0g7bwexyl( {
  "name": "Václavské náměstí, 1, Praha",
  "Status": {
    "code": 200,
    "request": "geocode"
  },
  "Placemark": [ {
    "id": "p1",
    "address": "Václavské náměstí 846/1, 110 00 Praha 1-Nové Město, Česká republika",
    "AddressDetails": {
   "Accuracy" : 8,
   "Country" : {
      "AdministrativeArea" : {
         "AdministrativeAreaName" : "Hlavní město Praha",
         "SubAdministrativeArea" : {
            "Locality" : {
               "DependentLocality" : {
                  "DependentLocalityName" : "Nové Město",
                  "PostalCode" : {
                     "PostalCodeNumber" : "110 00"
                  },
                  "Thoroughfare" : {
                     "ThoroughfareName" : "Václavské náměstí 846/1"
                  }
               },
               "LocalityName" : "Praha 1"
            },
            "SubAdministrativeAreaName" : "Praha"
         }
      },
      "CountryName" : "Česká republika",
      "CountryNameCode" : "CZ"
   }
},
    "ExtendedData": {
      "LatLonBox": {
        "north": 50.0873298,
        "south": 50.0810346,
        "east": 14.4271808,
        "west": 14.4208856
      }
    },
    "Point": {
      "coordinates": [ 14.4240332, 50.0841822, 0 ]
    }
  } ]
}
 )

Now I must store all these data into the database. I will not describe here some main procedure of how to insert some data into the MySQL database. But I will describe how get closest places stored in the database from the defined coordinates.

I will describe this procedure in the next article 😉

Share this:

One thought on “Google Maps API & PHP+MySQL – working with radius and distance

  1. I simply could not leave your website prior to suggesting that I actually enjoyed the usual info an individual supply for your visitors? Is going to be again incessantly to investigate cross-check new posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.