Print Shortlink

jQuery plugin for GeoLocation and Google Maps

Given below is an attempt at creating a jQuery plugin that displays a google map pointing out the current location of the user.

We’ve used HTML 5 Geo Location API to find out the coordinates (latitude and longitude) and pass them to the Google Map service which displays the map. The complete code has been bundled out as a jQuery plugin.

The HTML file is given below.

<!DOCTYPE html>
	<script src=""></script>
        <script src="jquery-maps.js"></script>
	<div id="mapplaceholder" style="width: 700px; height: 600px"></div>

The mapplaceholder element is passed as the input to the plugin method. Our map plugin method is present in jquery-maps.js. The jquery-maps.js file is shown below:

var mapObj = {
	mapElement : "",
	displayMap : function(){
		var mpElement = this.mapElement;
		   var lat = position.coords.latitude;
		   var lng = position.coords.longitude;
		   var latlng = new google.maps.LatLng(lat,lng);
	           var myOptions = {
		      zoom: 8,
		      center: latlng,
		      mapTypeId: google.maps.MapTypeId.ROADMAP
		   var googleMap = new google.maps.Map(mpElement,myOptions);
		   var marker = new google.maps.Marker({
		        position: latlng, 
		        map: googleMap, 
$ = function(){
	mapObj.mapElement = document.getElementById("mapplaceholder");

The mapObj object has the displayMap function which uses HTML5 geo location API and passes the coordinates to the Google maps API. In the map function we’ve used $.getScript to load the Google Maps script asynchronously. Notice the “callback=mapObj.displayMap” parameter in the query string. After loading the script the displayMap function is called automatically.

Leave a Reply

two + 7 =