• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Geolocation and Mapping
 

Geolocation and Mapping

on

  • 2,460 views

Mobile applications Development - Lecture 16 ...

Mobile applications Development - Lecture 16

Geolocation
Mapping
GMaps API v3

This presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy).

http://www.di.univaq.it/malavolta

Statistics

Views

Total Views
2,460
Views on SlideShare
2,458
Embed Views
2

Actions

Likes
4
Downloads
84
Comments
0

2 Embeds 2

http://us-w1.rockmelt.com 1
https://lscc.blackboard.com 1

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Geolocation and Mapping Geolocation and Mapping Presentation Transcript

    • Geolocation & Mapping Ivano Malavolta ivano.malavolta@univaq.ithttp://www.di.univaq.it/malavolta
    • Roadmap• Introduction• Geolocation• Google Maps Services** In this lecture we refer to Google Maps Services only because of space limitations. Other services, like Yahoo! Place Finder, can be used as valid alternatives
    • GeolocationGeolocation is the identification of the real-world geographic location of an object, like• mobile phone• Internet-connected computer terminalGeolocation may refer to the practice of assessing the location, or to the actual assessed location
    • MappingMapping usually refers to map-making and often used instead of cartography
    • Geolocation VS MappingGeolocation refers to geospatialdata collection and manipulationex. LatLon calculations, geocoding, etc.Mapping refers to the activity ofcreating a map through somecartographic worksex. maps, layers, markers, routes, etc.
    • Roadmap• Introduction• Geolocation• Google Maps Services** In this lecture we refer to Google Maps Services only because of their high understandability and stability. Other services, like Yahoo! Place Finder, can be used as valid alternatives
    • Geolocation navigator.geolocationProvides access for capturing location information for the device, like:• latitude• longitude• Speed
    • GeolocationThe API itself is agnostic of the underlying location information sourcesCommon sources of location information include• Global Positioning System (GPS)• location info from IP address, RFID, WiFi,GSM cell IDs, etc.No guarantee is given that the API returns the devices actual location
    • Geolocation MethodsThe geolocation object provides 3 methods:• geolocation.getCurrentPosition• geolocation.watchPosition• geolocation.clearWatch
    • getCurrentPositionIt returns the devices current positiongetCurrentPosition(win, [fail], [options]);win callback function with a Position parameterfail error callbackoptions geolocation options
    • watchPositionIt gets the devices position when a change in position has been detectedvar id = watchPosition(win, [fail], [options]);win callback function with a Position parameterfail error callbackoptions geolocation options
    • clearWatchStop watching the Geolocation referenced by the watch ID parameterclearWatch(watchID);watchID ID returned by geolocation.watchPosition
    • Options• frequency (Number) – How often to retrieve the position in milliseconds• enableHighAccuracy (Boolean) – Receive the best possible results• timeout (Number) – The maximum length of time (msec) that is allowed to pass from the call until the corresponding callback is invoked• maximumAge (Number) – Accept a cached position whose age is no greater than the specified time in milliseconds
    • The Position objectContains the data created by the geolocation APIIt is passed as argument to the success callbacks of getCurrentPosition and watchPositionProperties:coords:coords: A set of geographic Coordinates seconds in iOStimestamp: Creation timestamp in milliseconds
    • The Coordinates objectA set of properties that describe the geographic coordinates of a positionThe Coordinates object is created and populated by Cordova, and attached to the Position object
    • The Coordinates object Properties: • latitude (Number) – Latitude in decimal degrees • longitude (Number) – Longitude in decimal degrees • accuracy (Number) – Accuracy level of the latitude and longitude coordinates in metershttp://bit.ly/Ln6AtM
    • The Coordinates object null in Android • altitude (Number) – Height of the position in meters above the ellipsoid • altitudeAccuracy (Number) – Accuracy level of the altitude coordinate in metershttp://bit.ly/Ln7V3H
    • The Coordinates object • heading* (Number) – Direction of travel, specified in degrees counting clockwise relative to the true north • speed (Number) – Current ground speed of the device, specified in meters per second The Compass API in Cordova is exclusively dedicated to the heading propertyhttp://bit.ly/LnanXV
    • Position ErrorEncapsulates the error code resulting from a failed position capture operationIt contains a pre-defined error code pre- PositionError.PERMISSION_DENIED PositionError.POSITION_UNAVAILABLE PositionError.TIMEOUT
    • Examplevar options = { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true };navigator.geolocation.watchPosition(win, fail, options);function win(pos) { var el = ‘<div>Latitude: ‘ + pos.coords.latitude + </div>); el += ‘<div>Longitude: ‘ + pos.coords.longitude + </div>); el += ‘<div>timestamp: ‘ + pos.timestamp + </div>); $(‘#block’).html(el);}function fail(err) { console.log(err.code);}
    • Roadmap• Introduction• Geolocation• Google Maps Services** In this lecture we refer to Google Maps Services only because of their high understandability and stability. Other services, like Yahoo! Place Finder, can be used as valid alternatives
    • Google Maps API The Google Maps Javascript API lets you embed Google Maps in your app The latest version (v3) of this API is especially designed to be faster and more applicable to mobile deviceshttp://www.cibando.com
    • Goole Maps APIThe API provides a number of utilities for manipulating maps and adding content to the map through a variety of servicesYou can see it like a way to programmatically manage maps on http://maps.google.com
    • GMaps Basics google.maps.MapThis object represents a GMaps mapit will contain the maps along with all the other elements, like markers, polygons, etc.
    • GMaps BasicsHere is its constructor: google.maps.Map(htmlElement, options);• htmlElement – a reference to a HTML element where you want the map to be inserted • for example <div id=“map”></div>• options – an object literal containing a set of properties
    • GMaps BasicsThe options parameter may have these properties:• center (google.maps.LatLng) – the center of the map• zoom (Number) – the initial zoom-level of the map• mapTypeId (google.maps.MapTypeId) – what kind of map type that would initially be used – The most common type is google.maps.MapTypeId.ROADMAP
    • GMaps Basics• draggable (boolean) – if false, prevents the map from being dragged• minZoom (Number) – the minimum zoom level which will be displayed on the map• maxZoom (Number) – the maximum zoom level which will be displayed on the map• zoomControl (boolean) – if false, hides the control to zoom in the map• etc...
    • The LatLng objectIt is a point in geographical coordinates:• latitude• longitudeex. new google.maps.LatLng(57.8, 14.0);
    • The LatLngBounds objectIt represents a rectangle in geographical coordinates• south-west• north-eastex. new google.maps.LatLngBounds( new google.maps.LatLng(57.8, 14.0), new google.maps.LatLng(57.8, 14.0) );contains(pt), intersect(bounds), getCenter(), union(bounds), etc.
    • Map TypesYou must specifically set an initial map type at this time as wellmapTypeId: google.maps.MapTypeId.ROADMAPSupported types:• ROADMAP• SATELLITE• HYBRID• TERRAIN
    • Example// in your JS filevar options = { center: new google.maps.LatLng(-34.397, 150.644), zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP};var map = new google.maps.Map(document.getElementById(“map”), options);// somewhere in your HTML templates<div id=“map”></div>
    • GMaps EventsThere are 2 types of events:• User events – are propagated from the DOM to the Google Maps API – for example click• MVC state change notifications – reflect changes in Maps API objects and are named using a property_changed convention – for example the API will fire a zoom_changed event on a map when the maps zoom level changes
    • Map Event ListenersYou register for event notifications using the addListener() event handlergoogle.maps.event.addListener(obj, eventname, callback)• obj the object on which the event can occur obj: – ex. the whole map, a marker, etc.• eventname an event to listen for eventname: – ex. “click”, “center_changed”, “zoom_changed”, etc. – every objects can respond to different types of events• callback function to call when the specified event callback: occurs
    • DOM Object EventsIt allows you to capture events occurred on elements within the DOMaddDOMListener(obj, eventname, callback)It is similar to addListener, but here obj can be any element within the DOM
    • Examplevar map = new google.maps.Map(document.getElementById(“map”), opt);google.maps.event.addListener(map, click, function(event) { var marker = new google.maps.Marker({ position: event.latLng, map: map }); map.setCenter(marker.getPosition()); });
    • GMaps Overlays Overlays are objects that you “add” on the map like map, • points, • lines, • areas, • collection of other objects They are tied to latitude/longitude coordinates so they move when you drag or zoom the maphttp://bit.ly/Lztdac
    • http://bit.ly/LztJoV Types of Overlays in GMaps • Marker – represent single locations on the map – can be represented also by an icon • Polyline – an ordered sequence of locations – represent lines on the map In this lecture we will focus on markers & polylines only
    • Types of Overlays in GMaps • Polygon – an ordered sequence of locations – define a region on the map • Map Types – represent map layers – can replace base map tiles – can be displayed on top of base map tileshttp://bit.ly/LztFoVhttp://www.mapofthedead.com/
    • Types of Overlays in GMaps • Info Window – displays content within a popup balloon on top of a map – linked to a specific location • Custom Overlay – any DOM element that be positioned on the maphttp://bit.ly/LztFoV
    • MarkersMarkers identify locations on the mapMarkers are designed to be interactive you can attach event listeners to themex.marker = new google.maps.Marker({ // options });google.maps.event.addListener(marker, click, callback);
    • Marker OptionsThe google.maps.Marker constructor takes a single object literal specifying the initial properties of the marker• position – LatLng identifying the initial location of the marker• map – the Map object on which to place the marker – You can add the marker later by calling setMap() method – You can remove a marker by calling setMap() with null
    • Marker Options• animation – google.maps.Animation.DROP – google.maps.Animation.BOUNCE You may initiate an animation on an existing marker by calling setAnimation() on the marker object• draggable – makes the marker draggable on the map• icon – used to set a custom icon for the marker – it defines the URL of an image to be used as icon – The Google Maps API will size the icon automatically
    • PolylinesA Polyline object consists of an array of LatLngsIt creates a series of line segments that connect those locations in an ordered sequenceSimilarly to Marker, the constructor of Polyline takes an object literal containing the optionsAlso Polyline can react to user events
    • Polylines Options• path[] – array of LatLng, one for each point of the polyline• strokeColor – color of the lines in CSS syntax• strokeOpacity – opacity of the lines as a decimal number between 0 and 1• strokeWeight – the weight of the lines stroke in pixels• editable – boolean, specifies whether users can modify it or not
    • Examplevar map; // the map object, initialization omitted herevar coords = [ new google.maps.LatLng(37.772323, -122.214897), new google.maps.LatLng(21.291982, -157.821856), new google.maps.LatLng(-18.142599, 178.431), new google.maps.LatLng(-27.46758, 153.027892)];var polyline = new google.maps.Polyline({ path: coords, strokeColor: "#00FF00", strokeOpacity: 1.0, strokeWeight: 1});flightPath.setMap(map);
    • GMaps Services3 are the main services provided by GMaps:• Directions• Distance Matrix• Geocoding
    • DirectionsYou can calculate directions (using a variety of methods of transportation) by using the object google.maps.DirectionsServiceThis object communicates with Google Maps which receives direction requests and returns computed resultsYou can1. manage these directions results directly2. use the DirectionsRenderer object to render them
    • Direction Requests1. create an object of type DirectionsService2. create a DirectionsRequest object literal containing the input terms3. call DirectionsService.route() to initiate a request to the Directions service4. manage the results via a callback function manageRoutevar dirService = new google.maps.DirectionsService();var request = { origin: ”…”, destination: “…”, travelMode: google.maps.TravelMode.DRIVING};dirService.route(request, manageRoute);
    • Directions Request Properties
    • Directions ResultsWhen sending a directions request to the DirectionsService, you receive a response consisting of1. a DirectionsResult object – contains an array of DirectionsRoute object, each of them representing a route from the origin to destination2. a status code – OK, NOT_FOUND, ZERO_RESULTS, INVALID_REQUEST, etc.
    • Example of Route destination waypoints origin steps legshttp://goo.gl/maps/ZK4H
    • RoutesIt is an object literal with the following fields:• legs array of DirectionsLeg objects legs[]:• waypoint_order indicates the order of waypoints waypoint_order[]:• overview_path[]: array of LatLngs approximating the overview_path path of the resulting directions• bounds LatLngBounds containing the route bounds:• copyrights: text copyrights• warnings text warnings:
    • LegsIt is an object literal with the following fields:• steps[]: steps array of DirectionsStep objects• distance: distance total distance covered by this leg• duration: duration total duration of the leg• start_location: start_location the origin of the leg as LatLng• end_location: end_location the destination of the leg as LatLng• start_address: start_address the origin of the leg as text• end_address: the destination of the leg as text end_address
    • StepsIt is an object literal with the following fields:• instructions: instructions instructions for this step within as text• distance: distance total distance covered by this step• duration: duration total duration of the step• start_location: start_location the origin of the leg as LatLng• end_location: end_location the destination of the leg as LatLng
    • Examplehttp://bit.ly/KtJrUM
    • Distance MatrixIt is a service to compute1. travel distance2. journey durationbetween multiple origins and destinationsThis service does not return detailed route information you need the Directions Service for these
    • Distance Requestsgoogle.maps.DistanceMatrixService .getDistanceMatrix(options, callback)where• options – object literals containing origin, destination, travel modes, ...• callback – the function executed upon response
    • Distance Request Options• origins – array containing one or more address strings and/or LatLng• destinations – array containing one or more address strings and/or LatLng• travelMode – google.maps.TravelMode.DRIVING – google.maps.TravelMode.WALKING – google.maps.TravelMode.BICYCLING• unitSystem – google.maps.UnitSystem.METRIC – google.maps.UnitSystem.IMPERIAL• avoidHighways (boolean)• avoidTolls (boolean)
    • Distance ResponsesA successful call to the Distance Matrix service returns:• a DistanceMatrixResponse object• a DistanceMatrixStatus objectThese are passed to the callback function you specified in the request
    • DistanceMatrixResponseIt is an object containing the following properties:• originAddresses – array containing the locations passed in the origins field• destinationAddresses – array containing the locations passed in the destinations field• rows – array of DistanceMatrixResponseRow objects, with each row corresponding to an origin• elements – are children of rows, and correspond to a pairing of the rows origin with each destination – They contain status, distance, and duration information for each origin/destination pair
    • Examplevar origin = “L’Aquila, Italy";var destination = “London, England";var service = new google.maps.DistanceMatrixService();service.getDistanceMatrix({ origins: [origin], destinations: [destination], travelMode: google.maps.TravelMode.DRIVING, avoidHighways: false, avoidTolls: false}, callback);function callback(response, status) { if (status == google.maps.DistanceMatrixStatus.OK) { var t = response.rows[0].elements[0].distance.text; alert(t); }}
    • GeocodingIt is the process of converting addresses into geographical coordinatesex. “via Vetoio 1, L’Aquila” 42.362319,13.368514A geocoder may return more than a resultYou can also perform the inverse conversion reverse geocoding
    • Geocoding Requestsvar geocoder = google.maps.Geocoder();geocoder.geocode(options, callback);where• options (object literal) – address (String) geocoding – latLng (LatLng) reverse geocoding – bounds (LatLngBounds) – region (String) • see http://www.iana.org/assignments/language-subtag-registry• callback – the function executed upon response
    • Geocoding ResponsesThey are passed to the callback function as a GeocoderResults object
    • Examplegeocoder = new google.maps.Geocoder();var address = “via Vetoio 1, L’Aquila”;geocoder.geocode( { address: address}, callback);function callback(results, status) { if (status == google.maps.GeocoderStatus.OK) { for(result in results) { console.log(result.geometry.location); } } else { console.log(status); }}
    • What’s more?• Controls – UI elements to allow user interaction with the map – zoom, Street View, scale, map type• Layers – GeoRSS, KML, Fusion Tables, etc.• Map Types & Styles (see http://bit.ly/JEA6Nu) – custom styles, image overlays, etc.• StreetView Services• Drawing Library – drawing tools, geometry, etc.
    • Referenceshttps://developers.google.com/maps/documentation/javascript/