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>
<html>
<head>
	<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
        <script src="jquery-maps.js"></script>
	<script>
		$().ready(function(){
			$("#mapplaceholder").map();
		});
	</script>
</head>
<body>
	<div id="mapplaceholder" style="width: 700px; height: 600px"></div>
</body>
</html>

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;
		navigator.geolocation.getCurrentPosition(function(position){
		   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, 
		        title:"Welcome"
		   });   
		});
	}
};
$.fn.map = function(){
	mapObj.mapElement = document.getElementById("mapplaceholder");
	$.getScript("http://maps.googleapis.com/maps/api/js?sensor=true&callback=mapObj.displayMap");
};

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 =