Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

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!

Thursday, 21 March 2013


Parse
Parse is the cloud app platform for Windows 8, Windows Phone 8, iOS, Android, JavaScript, and OS X. With Parse, you can add a scalable and powerful backend in minutes and launch a full-featured mobile or web app in record time without ever worrying about server management. Parse offers push notifications, social integration, data storage, and the ability to add rich custom logic to your app’s backend with Cloud Code.

What is Parse.com ?


  • Backend for apps and websites
  • Store key/value data (think NoSQL in the cloud)
  • Store Any Files (Text, Image, PDF, etc)
  • Awesome API support for IOS, Android, Windows, Javascript, REST.
  • Free for most of us.

Features


  • User Management
  • Account creation w/o optional email verification.
  • Social Network Sign-in integration
  • Easy Push Notifications
  • Location Stuff.

So, how’s this work?


Well, let’s assume you’re a web developer. You can add the Parse JavaScript file on your page, get an API key, and start saving “objects” in the cloud with only a few lines of code. Parse frees you from setting up a server-side stack.
Think about this for a minute. Traditionally, you set up a server-side stack (LAMP, or RoR, ASP.NET, or something else), set up a database, and then interact with it via Ajax on the client. Parse just reduced all that work to a few lines of code.
In this tutorial, we’ll use Parse’s JavaScript SDK. You’re not limited to using only JavaScript, however; there are Parse libraries in many different languages, including PHP, NodeJS, Java, C# and more. You can find all the available libraries here.
Using Parse for Your Web-based Projects


Before we start, let’s take a minute and think how a traditional app could be created:

  • You would create a MySQL/Oracle database.
  • You may have a PHP/Java/ASP.NET class that is responsible for performing CRUD operations. Optionally, you could just have a bunch of functions.
  • You may use JavaScript and Ajax on the client-side to call the respective scripts and pass in query strings.
  • You would need to sanitize the input to protect against XSS attacks, as well as worry about database security in general.
  • If a collaborative app, you would need to track different users and manage their lists. More code, more tables, and more schemas.
  • You would need to make sure your database stays performant.


You get the idea. There’s a lot to think about and many areas to make mistakes. Parse handles these issues for us.


Create a Parse Account

Before you do anything, create a free Parse account. Then create a new app.




Download the Empty Project

Download the Blank Project with SDK from Downloads (Top Menu). The .zip file will contain index.html and css folder




Get the Application ID and Javascript Key

Go to Dashboard > “Friends List” Application > Settings Tab > Application Keys


The Client-Side



index.html

<html>
 <head>
  <title>Friends List | Parse App</title>
   <link href="css/reset.css" rel="stylesheet"></link>
   <link href="css/styles.css" rel="stylesheet"></link>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
   <script src="http://www.parsecdn.com/js/parse-1.2.2.min.js" type="text/javascript"></script>
 </head>
 <body>

  <div id="main">
   <center>
    <h2>Friends List</h2>
   </center>
   <hr />
   <div class="error" style="display: none;">
    Looks like there was a problem saving the test object.
         Make sure you've set your application ID and javascript key correctly in the call to <code>Parse.initialize</code> in this file.
       </div>
   <div class="success">
    <table>
     <tbody>
      <tr>
                     <td>Name: </td>
                     <td>
        <input id="friendsName" name="friendsName" type="text" />
                     </td>
                </tr>
      <tr>
       <td>Contact No:</td>
       <td><input id="friendsContactNo" name="friendsContactNo" type="text" />
              </td>
      </tr>
      <tr>
       <td></td>
                     <td>
        <button onclick="saveIntoParse()">Save</button>
                     </td>
                </tr>
     </tbody>
    </table>
    <hr />
    <table id="friendsList">
           </table>
   </div>
  </div>
  <script type="text/javascript">
       Parse.initialize("APPLICATION_ID", "JAVASCRIPT_KEY ");
   //    listDataFromParse();
      function saveIntoParse(){
           var name = document.getElementById("friendsName").value ;
           var contactNo = document.getElementById("friendsContactNo").value ;
        
           var FriendsList = Parse.Object.extend("FriendsList");
           var friendsListObject = new FriendsList();
           friendsListObject.save({friendsName: name,friendsContactNo:contactNo}, {
             success: function(object) {
                  alert("Successfully Saved.");
                  listDataFromParse();
             },
            error: function(model, error) {
             $(".error").show();
             }
           });
      }
      function listDataFromParse(){
           var FriendsList = Parse.Object.extend("FriendsList");
           var query = new Parse.Query(FriendsList);
           query.find({
             success: function(results) {
                // results is an array of Parse.Object.
                var i=0;
                var trData = '';
                $("#friendsList").html('');
                $("#friendsList").append('<tr><th style="width: 200px;">Name</th><th>Contact No</th></tr>');
                for(i=0;i < results.length;i++)
                {
                     $("#friendsList").append('<tr>' + '<td >' + results[i].get("friendsName") + '</td>' + '<td>' + results[i].get("friendsContactNo") + '</td>' + '</tr>');
                }
             },
             error: function(error) {
                // error is an instance of Parse.Error.
                alert("Error Occurred during Fetching data!!!");
     }
           });
      }
   </script>
 </body>
</html>

NOTE: Replace APPLICATION_ID and JAVASCRIPT_KEY with yours.

The important thing to note in the above code is the inclusion of the Parse JavaScript file,
<script src="http://www.parsecdn.com/js/parse-1.2.2.min.js"></script>.
This file contains the Parse object that we will interact with.




Browser View of index.html


Data Stored on Parse:


Similar way you can create your own custom classes before and access using Parse API from various languages (IOS,Android,Javascript,Windows,Rest API).


Parse has five types of classes:

  • User classes store user-specific information, and Parse provides sugar methods such as signUp(), login(), and more to help with user administration.
  • Installation classes are typically used to send push notifications for mobile apps. Yes, Parse supports push notifications to all clients.
  • Role classes help segregate users into specific roles, controlling access to read/write to other classes. This is called ACL (access control list) within Parse.
  • Product classes store in-app product data.
  • Custom classes are for anything else.



Pros and Cons

I want to stress is that Parse is not suitable for every type of project. Although the free plan is very generous, Parse is a paid service. It can get expensive if you go above certain limits. Luckily, the pricing model is very transparent, and you should be able to figure out how much your app can cost. Generally speaking, I use it for smaller projects where I can anticipate a certain cap when it comes to the number of API requests that I make. I have yet to try Parse for a large project.


One common issue with a service such as Parse is the lock-in effect.
If you use Parse for a small project that suddenly takes off, it can be difficult to move to a difference service or platform. As you can imagine, replacing Parse with your own back-end would entail a significant amount of refactoring. This doesn’t mean you shouldn’t use Parse, but it’s something to keep in mind.


Concluding Remarks

In this tutorial, we looked at how we can use Parse to create a relatively simple web application. I encourage you give the service a try, and make your own decision! Thanks.

Find me on Facebook! Follow me on Twitter!