Thursday 30 May 2013

Google Map Using Javascript

Things that are covered:
  1. Auto-complete Location using Google Places API
  2. Zoom Changed Event
  3. Radius Calculation
  4. Distance Calculation

Map.html

<!DOCTYPE html>
<head> 
    <title>Google Map Using Javascript</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
    <script type="text/javascript" src="googleMap.js"></script>
 <link type="text/css" rel="stylesheet" href="googleMap.css" />
</head>
<body>
 <div>
  <div style="float: left;">
   <form onsubmit="onSubmitSearchLocation(this.address.value); return false" >
    <input size="100" type="text" name="address" id="address" value="" placeholder="Location" title="Search">
    <input type="button" onclick="onSubmitSearchLocation(document.getElementById('address').value)" value="Search"/>
       </form>
   <div id="map"></div>
  </div>
  <div id="mapinfoDiv" style="float: right;width: 410px;">
   Map Info
   <button onclick="clearDivContent()">Clear Content</button>
   <hr>
   <div id="mapinfo"></div>
  </div>
 </div>
 <script type="text/javascript">
  initialize(37.4419, -122.1419);
  currentLocationView();
  function clearDivContent(){
   document.getElementById("mapinfo").innerHTML = '';
  }
 </script>
</body>
</html>


googleMap.js

var map;
var infowindow;
var markersArray = [];
var tempPlace ;

function initialize(selectedLat,selectedLong) {
 var pyrmont = new google.maps.LatLng(selectedLat,selectedLong);
 
 map = new google.maps.Map(document.getElementById('map'), {
   mapTypeId: google.maps.MapTypeId.ROADMAP,
   center: pyrmont,
   zoom: 10,
   streetViewControl: false
 });
 var searchedAddress = document.getElementById('address');
 var autocomplete = new google.maps.places.Autocomplete(searchedAddress);
 autocomplete.bindTo('bounds', map);
 google.maps.event.addListener(autocomplete, 'place_changed', function() {
  var place = autocomplete.getPlace();
  onSearchCLicked(place.geometry.location,searchedAddress.value);
  tempPlace = autocomplete.getPlace();
 });
 google.maps.event.addListener(map, 'zoom_changed', function() {
  console.log("zoom_changed: " + map.getZoom());
  document.getElementById("mapinfo").innerHTML = "Zoom Level: " + map.getZoom();
  getDistance();
  findDistance();
 });
}

function onSearchCLicked(locationSearched,searchedAddress)
{
 map.setCenter(locationSearched);
 map.setZoom(12);
 locationSearched = locationSearched.toString().replace("(","");
 locationSearched = locationSearched.toString().replace(")","");
 var latlng =  locationSearched.toString().split(",") ;
 var pyrmont = new google.maps.LatLng(latlng[0],latlng[1]);
 var request = {
   location: pyrmont,
   radius: 500000,
   name: searchedAddress
 };
 infowindow = new google.maps.InfoWindow();
 var service = new google.maps.places.PlacesService(map);
 service.search(request, callback);
}

function callback(results, status) {
 if(results.length > 0){
  clearOverlays();
 }
 if (status == google.maps.places.PlacesServiceStatus.OK) {
  //clearOverlays();
  for (var i = 0; i < results.length; i++) {
   createMarker(results[i]);
  }
 }else
 {
  if(tempPlace != '' && tempPlace != undefined)
  {
   clearOverlays();
   createMarker(tempPlace);
  }
 }
}

function clearOverlays() {
 if (markersArray) {
  for (i in markersArray) {
   markersArray[i].setMap(null);
  }
 }
 markersArray.length = 0;
}

function closeInfoWindows() {
 if (markersArray) {
  for (i in markersArray) {
   markersArray[i].infowindow.close();
  }
 }
}

function createMarker(place) {
 var searchedAddress = document.getElementById("address").value;
 var placeLoc = place.geometry.location;
 /*
   For Marker Image change
     http://powerhut.co.uk/googlemaps/custom_markers.php/
  */
 var image = new google.maps.MarkerImage(
   'map_marker.png',
   new google.maps.Size(23,53),
   new google.maps.Point(0,0),
   new google.maps.Point(12,53)
 );
 
 var marker = new google.maps.Marker({
  map: map,
  draggable: true,
  icon:image,
  position: place.geometry.location
 });
 markersArray.push(marker);
 google.maps.event.addListener(marker, "dragend", function(event) {
  placeLoc = this.getPosition();
  var locationSearched = placeLoc.toString().replace("(","");
  locationSearched = locationSearched.toString().replace(")","");
  var latlng =  locationSearched.toString().split(",") ;
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
   latLng: this.getPosition()
  }, function(responses){
   if (responses && responses.length > 0){
    var redirectURL;
    document.getElementById("address").value=responses[0].formatted_address;
    searchedAddress = '' ;
    infowindow.setContent("
Address:
" + responses[0].formatted_address + "
"); infowindow.open(map, marker); } else { alert('Cannot determine address at this location.'); } }); }); google.maps.event.addListener(marker, 'click', function() { placeLoc = this.getPosition(); var locationSearched = placeLoc.toString().replace("(",""); locationSearched = locationSearched.toString().replace(")",""); var latlng = locationSearched.toString().split(",") ; var geocoder = new google.maps.Geocoder(); geocoder.geocode({ latLng: this.getPosition() }, function(responses){ if (responses && responses.length > 0){ var redirectURL; document.getElementById("address").value=responses[0].formatted_address; infowindow.setContent("
Address:
" + responses[0].formatted_address + "
"); infowindow.open(map, marker); } else { alert('Cannot determine address at this location.'); } }); }); } function currentLocationView() { // Try HTML5 geolocation for redirecting to current location if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); map.setCenter(pos); map.setZoom(12); var latlng = []; latlng.push(position.coords.latitude); latlng.push(position.coords.longitude); }, function() { handleNoGeolocation(true); }); } else { // Browser doesn't support Geolocation handleNoGeolocation(false); } } function getDistance(){ bounds = map.getBounds(); if(bounds == undefined) return 0.18207856772 ; center = bounds.getCenter(); ne = bounds.getNorthEast(); // r = radius of the earth in statute miles var r = 3963.0; // Convert lat or lng from decimal degrees into radians (divide by 57.2958) var lat1 = center.lat() / 57.2958; var lon1 = center.lng() / 57.2958; var lat2 = ne.lat() / 57.2958; var lon2 = ne.lng() / 57.2958; // distance = circle radius from center to Northeast corner of bounds var dis = r * Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)); document.getElementById("mapinfo").innerHTML = document.getElementById("mapinfo").innerHTML + "
Radius:- Miles: " + (dis) + " KM: " + (dis*1.60934); return dis; } var Rm = 3961; // mean radius of the earth (miles) at 39 degrees from the equator var Rk = 6373; // mean radius of the earth (km) at 39 degrees from the equator /* main function */ function findDistance() { var t1, n1, t2, n2, lat1, lon1, lat2, lon2, dlat, dlon, a, c, dm, dk, mi, km; bounds = map.getBounds(); if(bounds == undefined) return 0.18207856772 ; center = bounds.getCenter(); ne = bounds.getNorthEast(); sw = bounds.getSouthWest(); // get values for lat1, lon1, lat2, and lon2 t1 = ne.lat(); n1 = ne.lng(); t2 = sw.lat(); n2 = sw.lng(); // convert coordinates to radians lat1 = deg2rad(t1); lon1 = deg2rad(n1); lat2 = deg2rad(t2); lon2 = deg2rad(n2); // find the differences between the coordinates dlat = lat2 - lat1; dlon = lon2 - lon1; // here's the heavy lifting a = Math.pow(Math.sin(dlat/2),2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon/2),2); c = 2 * Math.atan2(Math.sqrt(a),Math.sqrt(1-a)); // great circle distance in radians dm = c * Rm; // great circle distance in miles dk = c * Rk; // great circle distance in km // round the results down to the nearest 1/1000 mi = round(dm); km = round(dk); // display the result document.getElementById("mapinfo").innerHTML = document.getElementById("mapinfo").innerHTML + "
Distance between North East Lat-Lng and South West Lat-Lng:- KM2: " + km + " Miles2: " + mi ; document.getElementById("mapinfo").innerHTML = document.getElementById("mapinfo").innerHTML + " Lat 1: " + ne.lat() + " Lng 1: " + ne.lng() ; document.getElementById("mapinfo").innerHTML = document.getElementById("mapinfo").innerHTML + " Lat 2: " + sw.lat() + " Lng 2: " + sw.lng() ; } // convert degrees to radians function deg2rad(deg) { rad = deg * Math.PI/180; // radians = degrees * pi/180 return rad; } // round to the nearest 1/1000 function round(x) { return Math.round( x * 1000) / 1000; }
googleMap.css

      #map {
        height: 600px;
        width: 1150px;
        border: 1px solid #333;
        margin-top: 0.6em;
      }
      .pac-container
      {
       color: black;
       width: 370px !important;
      }

map_marker.png



Output






Thats it!

Get Location Based on IP Address

There are many vendor available in market that provides REST service to get Location based on IP Address. In our example we have used IPInfoDB.

Step 1) Create an account with IPInfoDB: http://ipinfodb.com/register.php



Once account is created, you will receive an Account Activation link from IPInfoDB:

Activate the account.

Step 2) Login into IPInfoDB and under Overview Tab, copy the API Key. Using this API Key we will    call IPInfoDB Rest API to get Location.

Step 3) Java Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class IPInfoDB {
 public static void main(String[] args) {
  new IPInfoDB().getClientLatLng("IP_ADDRESS");
 }
 
 public void getClientLatLng(String ip){
  if(ip!=null && !ip.equals(""))
  {
   try {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(
      "http://api.ipinfodb.com/v3/ip-city/?key={YOUR_API_KEY}&ip=" + ip);
    HttpResponse response = httpClient.execute(postRequest);
 
    if (response.getStatusLine().getStatusCode() != 201) {
     /*
      * throw new RuntimeException("Failed : HTTP error code : " +
      * response.getStatusLine().getStatusCode());
      */
     System.out.println("StatusCode: "
       + response.getStatusLine().getStatusCode());
    }
 
    BufferedReader br = new BufferedReader(new InputStreamReader(
      (response.getEntity().getContent())));
 
    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
     System.out.println(output);
    }
 
    httpClient.getConnectionManager().shutdown();
   } catch (MalformedURLException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}



OUTPUT:

StatusCode: 200
Output from Server .... 

OK;;10.162.1.1;IN;INDIA;GUJARAT;AHMEDABAD;-;23.0333;72.6167;+05:30
IP Info DB


Thats it!
Find me on Facebook! Follow me on Twitter!