Html 5 Geolocation/Reverse-Geolocation with Google Maps

PLEASE go to the specific page of this post, wordpress has an issue with executing javascript on the home page. Please use the link found here!

This is an expansion of what I started with my previous example. In this segment I will be taking the location retrieved and will apply it to Google Maps and will apply a push pin on the location retrieved and display the information retrieved from the reverse geolocation.


Latitude:
Longitude:



First lets analyze some parts of the HTML code to understand how everything ties in together.

<input id="go" onclick="initialize()" type="button" value="Update location values" align="middle" />

This part of the generates a button that will be labeled “Update location values” and upon the click of this button the initialize method will be called (found in the geolocation2.js file). This initializes the Map with a default location, which then gets updated soon after a new location has been detected. Then upon this new location being detected a pushpin will be applied to the map where the new location has been detected. Then the pushpin’s information window would then be filled with the data extracted from the new location that was retrieved. Which will later be explained in detail.

Further down the HTML code, we have 2 text input fields:

<input id="latitude" type="text" />
<input id="longitude" type="text" />

All these two field are used for is holding the latitude and longitude retrieved from the brand new location.

The source code for the new enhanced javascript file can be found below.

geolocation2.js

var map;
var marker;
var geocoder;
var infowindow;

<!-- Geo-Location Accessing code -->
$(document).ready(function () {
    // wire up button click
    $('#go').click(function () {
        // test for presence of geolocation
        if (navigator &amp;&amp; navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(geo_success, geo_error);
        } else {
            error('Geolocation is not supported.');
        }
    });
});

function geo_success(position) {
    printLatLong(position.coords.latitude, position.coords.longitude);
}

// The PositionError object returned contains the following attributes:
// code: a numeric response code
// PERMISSION_DENIED = 1
// POSITION_UNAVAILABLE = 2
// TIMEOUT = 3
// message: Primarily for debugging. It's recommended not to show this error
// to users.
function geo_error(err) {
    if (err.code == 1) {
        error('The user denied the request for location information.')
    } else if (err.code == 2) {
        error('Your location information is unavailable.')
    } else if (err.code == 3) {
        error('The request to get your location timed out.')
    } else {
        error('An unknown error occurred while requesting your location.')
    }
}

// output lat and long
function printLatLong(lat, long) {
	document.getElementById('latitude').value = lat;
	document.getElementById('longitude').value = long

	javascript:placeMarkerOnMap(lat, long);

}

function error(msg) {
    alert(msg);

	<!-- Replace div container data with error -->
	javascript:ReplaceContentInContainer('geolocData', msg)
}

// Take the latitude and longitude and apply it to a map
function placeMarkerOnMap(lat, long){	   

   var latitude = parseFloat(lat);
   var longitude = parseFloat(long);
   var current_location = new google.maps.LatLng(latitude, longitude);
   var mapOptions = {
          center: current_location,
          zoom: 8,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          zoomControl: true,
                zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.SMALL,
                    position: google.maps.ControlPosition.LEFT_CENTER
                },

          scaleControl: true
        };
   geocoder.geocode({'latLng': current_location}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          map.setZoom(11);
          marker = new google.maps.Marker({
              position: current_location,
              map: map
          });
          infowindow.setContent(results[1].formatted_address);
          infowindow.open(map, marker);
        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });

}

function initialize() {
	geocoder = new google.maps.Geocoder();
	infowindow = new google.maps.InfoWindow();
        var mapOptions = {
          center: new google.maps.LatLng(-34.397, 150.644),
          zoom: 8,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          zoomControl: true,
                zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.SMALL,
                    position: google.maps.ControlPosition.LEFT_CENTER
                },

          scaleControl: true,
        };
        map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);
}

function ReplaceContentInContainer(id,content) {
        var container = document.getElementById(id);
        container.innerHTML = content;
}

In addition to everything that was done in the previous example, there have been some minor changes for the sake of functionality. The first segment of code that will be executed would be the initialize method:

function initialize() {
	geocoder = new google.maps.Geocoder();
	infowindow = new google.maps.InfoWindow();
        var mapOptions = {
          center: new google.maps.LatLng(-34.397, 150.644),
          zoom: 8,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          zoomControl: true,
          zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.SMALL,
                    position: google.maps.ControlPosition.LEFT_CENTER
                },

          scaleControl: true,
        };
        map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);
}

In this method, several objects are instantiated and assigned. In particular, the Geocoder is an object that is used to reverse geocode a particular latitude and longitude retrieved from a particular location. The next object that is instantiated is the InfoWindow this is used to house the information extracted from the geocoded result.

The mapOption variable is self-explanatory, it basically enables some basic functionality with the particular map object that is being used. The final part of this method instantiates a map to the global variable that will be used for reference in another part of the code. The first parameter that is passed in is the div element that contains the particular map and the second parameter is the configuration of the map.

Continuing on (ignoring the code explained from the previous example), we find printLatLong method which was changed from the previous example:

// output lat and long
function printLatLong(lat, long) {
	document.getElementById('latitude').value = lat;
	document.getElementById('longitude').value = long

	javascript:placeMarkerOnMap(lat, long);

}

Being that this code is called after we have a particular new location, we then set the value of the two textboxes mentioned prior to the lat and long of the brand new location. Then we explicitly call a brand new method called placeMarkerOnMap which takes the latitude and longitude of the brand new location and then applies a pushpin onto the new location via:

// Take the latitude and longitude and apply it to a map
function placeMarkerOnMap(lat, long){	   

   var latitude = parseFloat(lat);
   var longitude = parseFloat(long);
   var current_location = new google.maps.LatLng(latitude, longitude);
   var mapOptions = {
          center: current_location,
          zoom: 8,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          zoomControl: true,
                zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.SMALL,
                    position: google.maps.ControlPosition.LEFT_CENTER
                },

          scaleControl: true
        };
   geocoder.geocode({'latLng': current_location}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          map.setZoom(11);
          marker = new google.maps.Marker({
              position: current_location,
              map: map
          });
          infowindow.setContent(results[1].formatted_address);
          infowindow.open(map, marker);
        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });

}

In this method we parse the two values and convert them into float values so that we can use them in the LatLng object which contains the location for this particular latitude and longitude. Immediately after is the configuration of the map, only difference is the center value has been changed to focus on our brand new location and the zoom has been set to 8, which zooms in further into the map, still following the most of the previous configuration.

Documentation for Geocoder
Documentation for Geocoder
Geocoder Documentation

Finally we have the geocoding part, where we first pass in our current location under a identified property of LatLng which is the current latitude and longitude. The next parameter is a function callback, which will be called after a geocoding result has been returned. This will be either the result(s) that were reverse-geocded or a failed result. Upon a successful result(s) then the map’s zoom configuration is changed to 11 then a marker is applied to the current location. Then after this, the InfoWindow is filled with formatted address from the 1st location of the array of results. and finally the InfoWindow is opened with our particular map and the marker that was just previous created. After this we have our final result of a map with our brand new location with pushpin on it!

Thanks for reading! I hope you have learned something new! If you have any issues post it in the comments.

Don’t forget to rate this post and if you have any feedback please post it in the comments as well!

Thanks,
Francisco