Upload
ivano-malavolta
View
2.326
Download
7
Embed Size (px)
DESCRIPTION
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
Citation preview
GeolocationGeolocation&
MappingIvano MalavoltaIvano Malavolta
http://www.di.univaq.it/malavolta
Roadmap
• Introduction• Geolocation• Geolocation• Google Maps Services*
* In this lecture we refer to Google Maps Services only because of spacelimitations. Other services, like Yahoo! Place Finder, can be used as validalternatives
Geolocation
GeolocationGeolocationGeolocationGeolocation is the identification of the real-world geographic location of an object, like
• mobile phone• Internet-connected computer terminal• Internet-connected computer terminal
Geolocation may refer to the practice of assessing the location, or to the actual assessed location
Mapping
MappingMappingMappingMapping usually refers to map-making and often used instead of cartography
Geolocation VS Mapping
GeolocationGeolocationGeolocationGeolocation refers to geospatial data collection and manipulationdata collection and manipulation
ex. LatLon calculations, geocoding, etc.
Mapping Mapping Mapping Mapping refers to the activity of creating a map through some creating a map through some cartographic works
ex. maps, layers, markers, routes, etc.
Roadmap
• Introduction• Geolocation• 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.geolocation
Provides access for capturing location information for the device, like:
• latitudelatitudelatitudelatitude
• longitudelongitudelongitudelongitude
• SpeedSpeedSpeedSpeed
Geolocation
The API itself is agnostic of the underlying location information sourcesinformation sources
Common sources of location information include
• Global Positioning System (GPS)Global Positioning System (GPS)Global Positioning System (GPS)Global Positioning System (GPS)
• location info from IP address, RFID, location info from IP address, RFID, location info from IP address, RFID, location info from IP address, RFID, WiFi,GSMWiFi,GSMWiFi,GSMWiFi,GSMcell IDs, etc.cell IDs, etc.cell IDs, etc.cell IDs, etc.cell IDs, etc.cell IDs, etc.cell IDs, etc.cell IDs, etc.
No guarantee is given that the API returns the device's actual location
Geolocation Methods
The geolocation object provides 3 methods:
• geolocation.getCurrentPositiongeolocation.getCurrentPositiongeolocation.getCurrentPositiongeolocation.getCurrentPosition
• geolocation.watchPositiongeolocation.watchPositiongeolocation.watchPositiongeolocation.watchPosition
• geolocation.clearWatchgeolocation.clearWatchgeolocation.clearWatchgeolocation.clearWatch
getCurrentPosition
It returns the device's current position
getCurrentPosition(win, [fail], [options]);
winwinwinwin
callback function with a PositionPositionPositionPosition parameter
failfailfailfail
error callback
optionsoptionsoptionsoptions
geolocation options
watchPosition
It gets the device's position when a change in position has been detectedbeen detected
var id = watchPosition(win, [fail], [options]);
winwinwinwincallback function with a PositionPositionPositionPosition parametercallback function with a PositionPositionPositionPosition parameter
failfailfailfailerror callback
optionsoptionsoptionsoptionsgeolocation options
clearWatch
Stop watching the Geolocation referenced by the watch ID parameterwatch ID parameter
clearWatch(watchID);
watchIDwatchIDwatchIDwatchID
ID returned by geolocation.watchPositionID returned by geolocation.watchPosition
Options
• frequency frequency frequency frequency (Number)– How often to retrieve the position in milliseconds– How often to retrieve the position in milliseconds
• enableHighAccuracyenableHighAccuracyenableHighAccuracyenableHighAccuracy (Boolean)– Receive the best possible results
• timeouttimeouttimeouttimeout (Number)– The maximum length of time (msec) that is allowed to pass from the call until the corresponding callback is invokedfrom the call until the corresponding callback is invoked
• maximumAgemaximumAgemaximumAgemaximumAge (Number)– Accept a cached position whose age is no greater than the specified time in milliseconds
The Position object
Contains the data created by the geolocation API
It is passed as argument to the success callbacks ofgetCurrentPosition and watchPosition
Properties:Properties:Properties:Properties:
coordscoordscoordscoords:::: A set of geographic Coordinates
timestamp:timestamp:timestamp:timestamp: Creation timestamp in millisecondsseconds in iOS
The Coordinates object
A set of properties that describe the geographic A set of properties that describe the geographic coordinates of a position
The Coordinates object is created and populated by Cordova, and attached to the Position object
The Coordinates object
Properties:Properties:Properties:Properties:
• latitudelatitudelatitudelatitude (Number)– Latitude in decimal degrees
• longitudelongitudelongitudelongitude (Number)– Longitude in decimal degrees
• accuracyaccuracyaccuracyaccuracy (Number)– Accuracy level of the latitude and longitude coordinates in meters
http://bit.ly/Ln6AtM
The Coordinates object
• altitudealtitudealtitudealtitude (Number)– Height of the position in meters above the ellipsoid
null in Android
– Height of the position in meters above the ellipsoid
• altitudeAccuracyaltitudeAccuracyaltitudeAccuracyaltitudeAccuracy (Number)– Accuracy level of the altitude coordinate in meters
http://bit.ly/Ln7V3H
The Coordinates object
• heading*heading*heading*heading* (Number)– Direction of travel, specified in degrees counting – Direction of travel, specified in degrees counting clockwise relative to the true north
• speedspeedspeedspeed (Number)– Current ground speed of the device, specified in meters per second
The Compass API in Cordova isexclusively dedicated to the
http://bit.ly/LnanXV
exclusively dedicated to the heading property
Position Error
Encapsulates the error code resulting from a failed position capture operationposition capture operation
It contains a prepreprepre----defined error codedefined error codedefined error codedefined error code
PositionError.PERMISSION_DENIED
PositionError.POSITION_UNAVAILABLEPositionError.POSITION_UNAVAILABLE
PositionError.TIMEOUT
Example
var 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• 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 appMaps in your app
The latest version (v3) of this API
is especially designed to be faster faster faster faster
and more applicable to mobilemobilemobilemobile
devicesdevicesdevicesdevices
http://www.cibando.com
Goole Maps API
The API provides a number of utilitiesutilitiesutilitiesutilities for manipulating maps and adding content adding content adding content adding content to the map through a maps and adding content adding content adding content adding content to the map through a variety of services
You can see it like a way to programmatically managemaps on http://maps.google.com
GMaps Basics
google.maps.Map
This object represents a GMaps map
it will contain the maps along with all the otherelements, like markers, polygons, etc.
GMaps Basics
Here is its constructor:
google.maps.Map(htmlElement, options);
• htmlElementhtmlElementhtmlElementhtmlElement– a reference to a HTML element where you want the map to be insertedmap to be inserted
• for example <div id=“map”></div>
• optionsoptionsoptionsoptions– an object literal containing a set of properties
GMaps Basics
The options parameter may have these properties:
• center center center center (google.maps.LatLng)– the center of the map
• zoom zoom zoom zoom (Number)– the initial zoom-level of the map
• mapTypeIdmapTypeIdmapTypeIdmapTypeId (google.maps.MapTypeId)– what kind of map type that would initially be used
– The most common type is google.maps.MapTypeId.ROADMAP
GMaps Basics
• draggabledraggabledraggabledraggable (boolean)– if false, prevents the map from being dragged– if false, prevents the map from being dragged
• minZoomminZoomminZoomminZoom (Number)– the minimum zoom level which will be displayed on the map
• maxZoommaxZoommaxZoommaxZoom (Number)– the maximum zoom level which will be displayed on the map
• zoomControlzoomControlzoomControlzoomControl (boolean)• zoomControlzoomControlzoomControlzoomControl (boolean)– if false, hides the control to zoom in the map
• etc...
The LatLng object
It is a point in geographical coordinates:
• latitude• latitude
• longitude
ex. new google.maps.LatLng(57.8, 14.0);
The LatLngBounds object
It represents a rectangle in geographical coordinates
• south-west• south-west
• north-east
ex. 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 Types
You must specifically set an initial map type at this time as welltime as well
mapTypeId: google.maps.MapTypeId.ROADMAP
Supported types:•• ROADMAP
• SATELLITE
• HYBRID
• TERRAIN
Example
// in your JS file
var options = {var 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);options);
// somewhere in your HTML templates
<div id=“map”></div>
GMaps Events
There are 2 types of events:
• User events– are propagated from the DOM to the Google Maps API
– for example click
• MVC state change notifications• 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 map's zoom level changes
Map Event Listeners
You register for event notifications using the addListener() event handleraddListener() event handler
google.maps.event.addListener(obj, eventname, callback)
• objobjobjobj: the object on which the event can occur– ex. the whole map, a marker, etc.
• eventnameeventnameeventnameeventname: an event to listen for– ex. “click”, “center_changed”, “zoom_changed”, etc.– every objects can respond to different types of events
• callbackcallbackcallbackcallback: function to call when the specified event occurs
DOM Object Events
It allows you to capture events occurred on elementswithin the DOMwithin the DOM
addDOMListener(obj, eventname, callback)
It is similar to addListener, but here obj can be anyelement within the DOMelement within the DOM
Example
var 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: mapmap: map
});
map.setCenter(marker.getPosition());
}
);
GMaps Overlays
Overlays are objects that you “add” on the mapOverlays are objects that you “add” on the mapOverlays are objects that you “add” on the mapOverlays are objects that you “add” on the map, like
• points,• points,
• lines,
• areas,
• collection of other objects
They are tied to latitude/longitude coordinates
� so they move when you drag or zoom the map
http://bit.ly/Lztdac
Types of Overlays in GMaps
• MarkerMarkerMarkerMarker– represent single locations on the map
http://bit.ly/LztJoV
– represent single locations on the map
– can be represented also by an icon
• PolylinePolylinePolylinePolyline– an ordered sequence of locations
– represent lines on the map– represent lines on the map
In this lecture we will focus on markers & polylines only
Types of Overlays in GMaps
• PolygonPolygonPolygonPolygon– an ordered sequence of locations– an ordered sequence of locations
– define a region on the map
• MapMapMapMap TypesTypesTypesTypes– represent map layers
– can replace base map tiles– can replace base map tiles
– can be displayed on top of
base map tiles
http://bit.ly/LztFoV
http://www.mapofthedead.com/
Types of Overlays in GMaps
• Info Info Info Info WindowWindowWindowWindow– displays content within a popup – displays content within a popup
balloon on top of a map
– linked to a specific location
• Custom Custom Custom Custom OverlayOverlayOverlayOverlay– any DOM element that be– any DOM element that be
positioned on the map
http://bit.ly/LztFoV
Markers
Markers identify locations on the map
Markers are designed to be interactiveMarkers are designed to be interactive
�you can attach event listeners to them
ex. ex. marker = new google.maps.Marker({
// options
});
google.maps.event.addListener(marker, 'click', callback);
Marker Options
The google.maps.Marker constructor takes a single object literal specifying the initial properties of the object literal specifying the initial properties of the marker
• positionpositionpositionposition– LatLng identifying the initial location of the marker
• mapmapmapmap• mapmapmapmap– 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
• animationanimationanimationanimation– google.maps.Animation.DROP– google.maps.Animation.DROP
– google.maps.Animation.BOUNCE
You may initiate an animation on an existing marker by calling setAnimation() on the marker object
• draggabledraggabledraggabledraggable– makes the marker draggable on the map– makes the marker draggable on the map
• iconiconiconicon– 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
Polylines
A Polyline object consists of an array of LatLngs
It creates a series of line segments that connect those locations in an ordered sequence
Similarly to Marker, the constructor of Polylinetakes an object literal containing the optionstakes an object literal containing the options
Also Polyline can react to user events
Polylines Options
• path[]– array of LatLng, one for each point of the polyline– 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• strokeWeight– the weight of the line's stroke in pixels
• editable– boolean, specifies whether users can modify it or not
Example
var map; // the map object, initialization omitted here
var 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({var polyline = new google.maps.Polyline({
path: coords,
strokeColor: "#00FF00",
strokeOpacity: 1.0,
strokeWeight: 1
});
flightPath.setMap(map);
GMaps Services
3 are the main services provided by GMaps:
• DirectionsDirectionsDirectionsDirections
• DistanceDistanceDistanceDistance MatrixMatrixMatrixMatrix
• GeocodingGeocodingGeocodingGeocoding
Directions
You can calculate directions (using a variety of methods of transportation) by using the object
google.maps.DirectionsService
This object communicates with Google Maps which receives direction requests and returns computed results
You can1. manage these directions results directly2. use the DirectionsRenderer object to render them
Direction Requests
1. create an object of type DirectionsService2. create a DirectionsRequest object literal containing
the input terms2. 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 manageRoute
var dirService = new google.maps.DirectionsService();var dirService = new google.maps.DirectionsService();
var request = {
origin: ”…”,
destination: “…”,travelMode: google.maps.TravelMode.DRIVING
};
dirService.route(request, manageRoute);
Directions Request Properties
Directions Results
When sending a directions request to the DirectionsService, you receive a response consisting of you receive a response consisting of
1. a DirectionsResultDirectionsResultDirectionsResultDirectionsResult object– contains an array of DirectionsRoute object, each of
them representing a route from the origin to destination
2. a status codestatus codestatus codestatus code2. a status codestatus codestatus codestatus code– OK, NOT_FOUND, ZERO_RESULTS, INVALID_REQUEST, etc.
Example of Route
destination
origin
waypoints
steps
http://goo.gl/maps/ZK4H
legs
Routes
It is an object literal with the following fields:
• legslegslegslegs[]: array of DirectionsLeg objects
• waypoint_orderwaypoint_orderwaypoint_orderwaypoint_order[]: indicates the order of waypoints
• overview_pathoverview_pathoverview_pathoverview_path[]: array of LatLngs approximating the path of the resulting directions
• boundsboundsboundsbounds: LatLngBounds containing the route• boundsboundsboundsbounds: LatLngBounds containing the route
• copyrightscopyrightscopyrightscopyrights: text
• warningswarningswarningswarnings: text
Legs
It is an object literal with the following fields:
• stepsstepsstepssteps[]: array of DirectionsStep objects
• distancedistancedistancedistance: total distance covered by this leg
• durationdurationdurationduration: total duration of the leg
• start_locationstart_locationstart_locationstart_location: the origin of the leg as LatLng
• end_locationend_locationend_locationend_location: the destination of the leg as LatLng• end_locationend_locationend_locationend_location: the destination of the leg as LatLng
• start_addressstart_addressstart_addressstart_address: the origin of the leg as text
• end_addressend_addressend_addressend_address: the destination of the leg as text
Steps
It is an object literal with the following fields:
• instructionsinstructionsinstructionsinstructions: instructions for this step within as text
• distancedistancedistancedistance: total distance covered by this step
• durationdurationdurationduration: total duration of the step
• start_locationstart_locationstart_locationstart_location: the origin of the leg as LatLng
• end_locationend_locationend_locationend_location: the destination of the leg as LatLng• end_locationend_locationend_locationend_location: the destination of the leg as LatLng
Example
http://bit.ly/KtJrUM
Distance Matrix
It is a service to compute
1.1.1.1. travel distancetravel distancetravel distancetravel distance1.1.1.1. travel distancetravel distancetravel distancetravel distance
2.2.2.2. journey durationjourney durationjourney durationjourney duration
between multiple origins and destinations
This service does not return detailed route informationThis service does not return detailed route information
� you need the Directions Service for these
Distance Requests
google.maps.DistanceMatrixService
.getDistanceMatrix(options, callback).getDistanceMatrix(options, callback)
where
• optionsoptionsoptionsoptions– object literals containing origin, destination, travel modes, ...
• callbackcallbackcallbackcallback• callbackcallbackcallbackcallback– the function executed upon response
Distance Request Options
• originsoriginsoriginsorigins– array containing one or more address strings and/or LatLng
• destinationsdestinationsdestinationsdestinations• destinationsdestinationsdestinationsdestinations– array containing one or more address strings and/or LatLng
• travelModetravelModetravelModetravelMode– google.maps.TravelMode.DRIVING– google.maps.TravelMode.WALKING– google.maps.TravelMode.BICYCLING
• unitSystemunitSystemunitSystemunitSystem– google.maps.UnitSystem.METRIC– google.maps.UnitSystem.IMPERIAL
• avoidHighwaysavoidHighwaysavoidHighwaysavoidHighways (boolean)• avoidTollsavoidTollsavoidTollsavoidTolls (boolean)
Distance Responses
A successful call to the Distance Matrix service returns:returns:
• a DistanceMatrixResponse object
• a DistanceMatrixStatus object
These are passed to the callback function you specified in the request
DistanceMatrixResponse
It is an object containing the following properties:
• originAddressesoriginAddressesoriginAddressesoriginAddresses– array containing the locations passed in the origins field
• destinationAddressesdestinationAddressesdestinationAddressesdestinationAddresses– array containing the locations passed in the destinations field
• rowsrowsrowsrows– array of DistanceMatrixResponseRow objects, with each row
corresponding to an origincorresponding to an origin
• elementselementselementselements– are children of rows, and correspond to a pairing of the row's
origin with each destination– They contain status, distance, and duration information for each
origin/destination pair
Example
var 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);}, callback);
function callback(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var t = response.rows[0].elements[0].distance.text;
alert(t);
}
}
Geocoding
It is the process of convertingconvertingconvertingconverting addresses intogeographical coordinatesgeographical coordinates
ex.
“via Vetoio 1, L’Aquila” � 42.362319,13.368514
A geocoder may return more than a resultA geocoder may return more than a result
You can also perform the inverse conversion
� reverse reverse reverse reverse geocodinggeocodinggeocodinggeocoding
Geocoding Requests
var geocoder = google.maps.Geocoder();
geocoder.geocode(options, callback);geocoder.geocode(options, callback);
where• optionsoptionsoptionsoptions (object literal)
– address (String) � geocoding– latLng (LatLng) � reverse geocoding– latLng (LatLng) � reverse geocoding– bounds (LatLngBounds) – region (String)
• see http://www.iana.org/assignments/language-subtag-registry
• callbackcallbackcallbackcallback– the function executed upon response
Geocoding Responses
They are passed to the callback function as a GeocoderResults object
Example
geocoder = 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?
• ControlsControlsControlsControls
– UI elements to allow user interaction with the map– UI elements to allow user interaction with the map
– zoom, Street View, scale, map type
• LayersLayersLayersLayers
– GeoRSS, KML, Fusion Tables, etc.
• MapMapMapMap TypesTypesTypesTypes & & & & StylesStylesStylesStyles (see http://bit.ly/JEA6Nu)
– custom styles, image overlays, etc.– custom styles, image overlays, etc.
• StreetViewStreetViewStreetViewStreetView ServicesServicesServicesServices
• DrawingDrawingDrawingDrawing LibraryLibraryLibraryLibrary
– drawing tools, geometry, etc.
References
https://developers.google.com/maps/documentation/javascript/