Like us on Facebook and stand a chance to win pen drives!

Showing posts with label javaScript. Show all posts
Google Map Multiple WayPoints
Google Map Multiple WayPoints


<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script type="text/javascript">

        var myRouter = {
            map_: null,
            directionsHelper_: null,

            stores: [
                    {name: "Thalawa Station", location: new google.maps.LatLng(8.231796, 80.348333)},
                    {name: "Maho Station", location: new google.maps.LatLng(7.8228, 80.2778)},
                    {name: "Mirigama Station", location: new google.maps.LatLng(7.242555, 80.126472)},
                    {name: "Veyangoda Station", location: new google.maps.LatLng(7.153015, 80.058488)},
                    {name: "Gampaha Station", location: new google.maps.LatLng(7.093543, 79.993703)}
                ],

            calcRoute: function() {

                var waypts = [];

                for (var i in this.stores) {
                    waypts.push({
                        location: this.stores[i].location,
                        stopover:true
                    });
                }
                var request = {
                    //origin: new google.maps.LatLng(8.344216, 80.410917),
					origin: "Anuradhapura Railway Station",
                    destination: "Colombo Fort Railway Station",
                    waypoints: waypts,
                    optimizeWaypoints: true,
                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                };

                var _SELF = this;
                this.directionsHelper_.route(request, function(response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        _SELF.directionsDisplay_.setDirections(response);
                        return;
                    }
                    console.log('Directions Status: ' + status);
                });
            },

            init: function(mapid) {

                this.directionsHelper_ = new google.maps.DirectionsService();
                this.directionsDisplay_ = new google.maps.DirectionsRenderer();

                var center = new google.maps.LatLng(8.344216, 80.410917);
                var myOptions = {
                    zoom:7,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    center: center
                }
                this.map_ = new google.maps.Map(document.getElementById(mapid), myOptions);
                this.directionsDisplay_.setMap(this.map_);

                this.calcRoute();
            }
        };

        $(document).ready(function() {
            myRouter.init('map');
        });

    </script>
    <style type="text/css">
        #map {
            height: 500px;
            width: 600px;
            border: 1px solid #000;
        }
    </style>
</head>
<body>
    <div id="map"></div>
</body>
</html>
Google Map Polygon
Google Map Polygon

How to get coordinates of a polygon?


How to delete a polygon?



<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>Drawing Tools</title>
<script src="jquery-1.10.2.js"></script>
 
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false&libraries=drawing"></script>
<style type="text/css">
#map, html, body {
padding: 0;
margin: 0;
height: 100%;
 
}
 
#panel {
width: 200px;
font-family: Arial, sans-serif;
font-size: 13px;
float: right;
margin: 10px;
}
 
#color-palette {
clear: both;
}
 
.color-button {
width: 14px;
height: 14px;
font-size: 0;
margin: 2px;
float: left;
cursor: pointer;
}
 
#delete-button {
margin-top: 5px;
}
</style>
<script type="text/javascript">
var drawingManager;
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};
var polygons = [];
var drawingManager = null;
var bermudaTriangle;
 
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
 
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
 
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
 
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
 
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
 
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
 
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
 
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
 
function setSelectedShapeColor(color) {
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set('strokeColor', color);
} else {
selectedShape.set('fillColor', color);
}
}
}
 
function makeColorButton(color) {
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function() {
selectColor(color);
setSelectedShapeColor(color);
});
 
return button;
}
 
function buildColorPalette() {
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
 
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(22.344, 114.048),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
 
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
 
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
 
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
 
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
 
buildColorPalette();
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
polygons.push(polygon);
 
});
 
}
google.maps.event.addDomListener(window, 'load', initialize);
 
function pointsToText() {
 
for (i = 0; i < polygons.length; i++) {
var coordinates = (polygons[i].overlay.getPath().getArray());
 
for (i = 0; i < coordinates.length; i++) {
 
$("#points").append("(" + coordinates[i]['k'] + "," + coordinates[i]['A'] + "),");
 
}
}
}
</script>
</head>
<body>
<div id="panel">
<div id="color-palette"></div>
<div>
<button id="delete-button">Delete Selected Shape</button>
</div>
<div>
<input type="button" onclick="pointsToText()" value="Get Coordinates">
<textarea id="points" cols="30" rows="20"></textarea><br>
 
</div>
 
</div>
<div id="map"></div>
 
</body>
</html>
Flicker API
Flicker API



<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>Flicker Image Search API Demo</title>
</head>
<body>
Search for <b>girls, dogs, cakes</b> ...etc)
<br />
<input id="searchterm" />
<button id="search">search</button>
<div id="results"></div>
<script>
$("#search").click(function(){
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: $("#searchterm").val(),
format: "json"
},
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).prependTo("#results");
if ( i == 10 ) return false;
});
});
});
</script>
</body>
</html>


In this tutorial, I 'll introduce you to YOURS, an OpenSource directions API. There are few OpenSource directions APIs available such as MapQuest, GeoSmart, Nominatim in addition to YOURS. However in my opinion, YOURS is the best and a good alternative to Google Directions which is the most popular Directions provider obviously.

The flexibility of usage has given more power in YOURS over other APIs in the same family. MapQuest is nice but it is not working for many geographical locations of the world other than North America and Europe. Nominatim is poor in its functional level and has less support for geographical diversity.

According to YOURS doucmentation, the API provide following features.

  • Generate fastest or shortest routes in different modes:

    • using all available roads for Car, Bicycle and Pedestrians .

    • using only national, regional or local cycle routes/networks for Bicycle.

  • Unlimited via points (waypoints) to make complex routes.

  • Drag and drop waypoints moving.

  • Drag and drop waypoint ordering.

  • Geolocation: Lookup street- and placenames to determine their coordinates.

  • Reverse geolocation: Lookup coordinates to determing their street- and placenames.You can read other features in doucmentation.

Example URL


http://www.yournavigation.org/api/1.0/gosmore.php?format=kml&flat=52.215676&flon=5.963946&tlat=52.2573&tlon=6.1799&v=motorcar&fast=1&layer=mapnik

This tutorial provides sample code for accessing the API in JavaScript. As JavaScript does not allow  cross domain requests we 're using a proxy which accepts requests from client, forward it to the API and send back server response. The proxy is written in PHP using CURL which is more safe than file_get_contents() and similar content loading functions.

We are using OpenLayers map with a vector layer which is going get features from server response. The route is drawn on map using vector data.

The API also provides travelling time, distance and turn by turn directions.

Demo

client.html


<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="description" content="OpenSource Directions API Demo - YOURS Navigation API">
        <title>OpenSource Directions API Demo</title>
        <link rel="stylesheet" href="http://demos.site11.com/assets/css/style.css">
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script src="http://openlayers.org/api/OpenLayers.js"></script>
            var lon = 0;
            var lat = 0;
            var zoom = 0;

            var wgs84 = new OpenLayers.Projection("EPSG:4326");
            var mercator = new OpenLayers.Projection("EPSG:900913");

            $(document).ready(function(){
                layer = new OpenLayers.Layer.OSM("OSM");
                geojson_layer = new OpenLayers.Layer.Vector("GeoJSON", {
                    styleMap: new OpenLayers.StyleMap({
                        strokeColor: "#F00",
                        projection: mercator
                    }),
                    strategies: [new OpenLayers.Strategy.Fixed()],
                    protocol: new OpenLayers.Protocol.HTTP({
                        url: 'proxy.php?flat=6.9344&flon=79.8428&tlat=7.2844590&tlon=80.637459&v=motorcar&fast=1&layer=mapnik',
                        format: new OpenLayers.Format.GeoJSON()

                    })
                });

                var options = {
                    div : "map",
                    projection : wgs84,
                    units: "dd",
                    numZoomLevels : 7
                };
                var map = new OpenLayers.Map(options);

                map.addLayers([layer,geojson_layer]);
                map.setCenter(new OpenLayers.LonLat(79.8428, 6.9344).transform(wgs84,mercator), 12);

                //Get Directions
                $.ajax({
                    type: 'GET',

                    dataType: 'json',
                    url: 'proxy.php?flat=6.9344&flon=79.8428&tlat=7.2844590&tlon=80.637459&v=motorcar&fast=1&layer=mapnik',
                    cache: false,
                    success: function(response){
                        $("#travel_time").html(response.properties.traveltime);
                        $("#distance").html(response.properties.distance + ' miles');
                        $("#directions").html(response.properties.description);
                    },error: function(){

                    }
                });

            });

        </script>
        <style type="text/css">
            #map{
                width: 800px;
                height: 400px;
                border: 2px solid black;
                padding:0;
                margin:0;
            }
        </style>
    </head>
    <body>
 <div id="map" style="width: 700px; height: 300px;margin-bottom : 50px;" align="center"></div>
                    <p><b>Travel Time</b></p><div id="travel_time"></div><br>
                    <p><b>Distance</b></p><div id="distance"></div><br>
                    <p><b>Directions</b></p><div id="directions"></div>
  </body>
</html>
Proxy.php

<?php
$flat = $_GET['flat'];
$flon = $_GET['flon'];
$tlat = $_GET['tlat'];
$tlon = $_GET['tlon'];
$v = $_GET['v'];
$fast = $_GET['fast'];
$layer = $_GET['layer'];

$myURL = "http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&instructions=1&flat=".$flat."&flon=".$flon."&tlat=".$tlat."&tlon=".$tlon."&v=".$v."&fast=".$fast."&layer=".$layer;
$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $myURL

));

$resp = curl_exec($curl);
curl_close($curl);
echo $resp;
?>
HTML5 LocalStorage
HTML5 LocalStorage

This tutorial assumes that you are already familiar with HTML5  localStorage.

Although HTML5  localStorage is very useful, its usage is restricted to key value mechanism. Key and value is stored in string format despite what we need. For an instance, though you can specify a boolean type (either true or false) as the value, it is stored as a string.

What if we need to store multiple items as the value for a certain key. This can be little bit tricky if you gonna place an array directly as the value. When we scratch the surface of localStorage basic principles this is not possible. However you can come up with your own solutions that might work for you.

This tutorial demonstrates a simple way of handling above problem using json. We gonna store array as a json string. So nothing new here.

First add jQuery library as we are using some jQuery functions.


<script type="text/javascript">
 var favorites_str = localStorage.getItem('my_favorites');
 if(favorites_str == null) {
 favorites = [];
 favorites.push({ "name":"keshi", "id":"6" });
 } else{
 favorites = JSON.parse(favorites_str);
 favorites.push({ "name":"sara", "id":"6" });
 
}
 localStorage.setItem('my_favorites',JSON.stringify(favorites));
 </script>

To verify that above script is functioning please copy and run below script. It will make things easy, if you put this code in  a separate file.

<script type="text/javascript">
 var data = localStorage.getItem('my_favorites');
 if(data == null){
 alert("0 favorites");
 }else{
 favorites = JSON.parse(data);
 $.each(favorites, function(index,item){
 alert(item.name);
 
});
 }
 </script>
Geojson
Geojson


Let's see how we can add a vector layer to OpenLayers map with the help of  GeoJSON response received from the server. Web Server can produce response in GML, GeoJSON, XML...etc after running a spatial query.
OpenLayers has Format classes for interpreting each kind of response.
This response consists of raw data which should be converted to features and added to a vector layer in order to render with OpenLayers.


var newLayer = new OpenLayers.Layer.Vector("Filtered by Zoom Level", {
strategies: [new OpenLayers.Strategy.BBOX(),
],
 
protocol: new OpenLayers.Protocol.HTTP({
url: "http://localhost/test/a.php?start=79.891119%207.078768&end=81.000609%207.940130&method=SPD",
format: new OpenLayers.Format.GeoJSON({
externalProjection: new OpenLayers.Projection("EPSG:4326"),
internalProject: new OpenLayers.Projection("EPSG:900913")
})
}),
 
//filter: filter,
 
// styleMap: styleMap,
format: new OpenLayers.Format.GeoJSON({
externalProjection: new OpenLayers.Projection("EPSG:4326"),
internalProject: new OpenLayers.Projection("EPSG:900913")
})
 
});
map.addLayers([newLayer]);


Another Way


var newLayer = new OpenLayers.Layer.Vector("SPD", {
isBaseLayer: false,
 
styleMap: new OpenLayers.StyleMap({'default':{
strokeColor: "#F00",
strokeOpacity: 1,
strokeWidth: 2,
fillColor: "#FF5500",
fillOpacity: 0.5,
label : "${ad}",
fontSize: "8px",
fontFamily: "Courier New, monospace",
labelXOffset: "0.5",
labelYOffset: "0.5"
}})
});
 
 
OpenLayers.Request.GET({
url: "http://localhost/test/a.php?start=79.891119%207.078768&end=81.000609%207.940130&method=SPD",
headers: {'Accept':'application/json'},
success: function (req)
{
var g = new OpenLayers.Format.GeoJSON();
var feature_collection = g.read(req.responseText);
newLayer.destroyFeatures();
newLayer.addFeatures(feature_collection);
}
});
map.addLayers([newLayer]);


Demo

If you know the latitude and longitude of a particular location, you can get the relevant address details such as city, state, region, country...etc. This process is known as Reverse Geocoding. In this post I 'm gonna show you how this could be achieved with famous Google Map API. This entire post is based on one API request. Look at below code.


http://maps.googleapis.com/maps/api/geocode/json?latlng=-37.814251,144.963169&sensor=false

Enter above line in the browser bar to see a whole bunch of location details for the geographical point (-37.814251,144.963169) in lat lng format.
Pretty Simple. Here I'm using Google Map JavaScript API V3. All you need to do is to parse the json response to extract the information whatever you need.


jQuery.ajax({
url: 'http://maps.googleapis.com/maps/api/geocode/json?latlng=-37.814251,144.963169&sensor=false',
type: 'POST',
dataType: 'json',
success: function(data) {
if(data.status == 'OK')
{
 
alert(data.results[1].formatted_address);
alert(data.results[1].address_components[0].long_name);
alert(data.results[1].address_components[1].long_name);
 
}
 
},
error: function(xhr, textStatus, errorThrown) {
alert("Unable to resolve your location");
 
}
});


Demo


<!DOCTYPE html>
<html>
  <head>
    <meta charset="<a>utf-8</a>">
    <title>Street View service</title>
    <link href="<a href="view-source:https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css">/maps/documentation/javascript/examples/default.css</a>" rel="<a>stylesheet</a>">
    <script src="<a href="view-source:https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false">https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false</a>"></script>
    <script>
function initialize() {
  var fenway = new google.maps.LatLng(42.345573,-71.098326);
  var mapOptions = {
    center: fenway,
    zoom: 14,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(
      document.getElementById('map-canvas'), mapOptions);
  var panoramaOptions = {
    position: fenway,
    pov: {
      heading: 34,
      pitch: 10
    }
  };
  var panorama = new  google.maps.StreetViewPanorama(document.getElementById('pano'),panoramaOptions);
  map.setStreetView(panorama);
}
 
google.maps.event.addDomListener(window, 'load', initialize);
 
    </script>
  </head>
  <body>
    <div id="<a>map-canvas</a>" style="<a>width: 400px; height: 300px</a>"></div>
    <div id="<a>pano</a>" style="<a>position:absolute; left:410px; top: 8px; width: 400px; height: 300px;</a>"></div>
  </body>
</html>

Copyright © 2012 The Code Junction.