Google Maps w/ location

This html / jquery example will show you how to search for the browser location on googlemaps, also it can be
used for GPS locations.

The HTML:


<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="user-scalable=no,width=device-width" />
   <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
   <script src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
   <script src="gmap.js"></script>
</head>
<body>
   <div id="mapPage">
      <div id="mapCanvas">
         <script>
           $(document).ready(function(){
             gmap.getUserLoc();
             gmap.loadMap();
           });
          </script>
          loading position... and map..
         </div>
      </div>
   </body>
</html>

This section of javascript should be saved in same folder as gmap.js:


gmap={
pos: null,
getUserLoc: function(){
  gmap.pos=null;
  if(navigator.geolocation){
     var timeoutVal = 10 * 1000 * 1000;
     navigator.geolocation.getCurrentPosition(
     gmap.showPos,
     gmap.getError,
     { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
  );
  } else{
     alert("Sorry, not supported");
  }
},
getError: function(error){
   var errors = {
     1: 'No permissions',
     2: 'No position',
     3: 'Timeout',
     };
alert("Error: " + errors[error.code]);
},
showPos: function(pos){
   gmap.pos = [pos.coords.latitude, pos.coords.longitude];
},
draw: function(){
var pos = new google.maps.LatLng(gmap.pos[0], gmap.pos[1]);
var options = {
  zoom: 15,
  center: pos,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
var $map = $("#mapCanvas");
var width=$(document).width()-30, height=$(document).height()-44;
$map.height(height);
$map.width(width);
var map = new google.maps.Map($map[0], options);
},
loadMap: function(){
  if(gmap.pos!=null){
    gmap.draw();
  }else setTimeout("gmap.draw()",1000);
}
};

One thought on “Google Maps w/ location

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s