Code coverage report for src/map/ext/Map.Geolocation.js

Statements: 4.35% (1 / 23)      Branches: 0% (0 / 18)      Functions: 0% (0 / 4)      Lines: 4.35% (1 / 23)     

All files » src/map/ext/ » Map.Geolocation.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89        1                                                                                                                                                                        
/*
 * Provides L.Map with convenient shortcuts for using browser geolocation features.
 */
 
L.Map.include({
	_defaultLocateOptions: {
		watch: false,
		setView: false,
		maxZoom: Infinity,
		timeout: 10000,
		maximumAge: 0,
		enableHighAccuracy: false
	},
 
	locate: function (/*Object*/ options) {
 
		options = this._locationOptions = L.extend(this._defaultLocateOptions, options);
 
		if (!navigator.geolocation) {
			this._handleGeolocationError({
				code: 0,
				message: "Geolocation not supported."
			});
			return this;
		}
 
		var onResponse = L.bind(this._handleGeolocationResponse, this),
			onError = L.bind(this._handleGeolocationError, this);
 
		if (options.watch) {
			this._locationWatchId =
			        navigator.geolocation.watchPosition(onResponse, onError, options);
		} else {
			navigator.geolocation.getCurrentPosition(onResponse, onError, options);
		}
		return this;
	},
 
	stopLocate: function () {
		if (navigator.geolocation) {
			navigator.geolocation.clearWatch(this._locationWatchId);
		}
		return this;
	},
 
	_handleGeolocationError: function (error) {
		var c = error.code,
		    message = error.message ||
		            (c === 1 ? "permission denied" :
		            (c === 2 ? "position unavailable" : "timeout"));
 
		if (this._locationOptions.setView && !this._loaded) {
			this.fitWorld();
		}
 
		this.fire('locationerror', {
			code: c,
			message: "Geolocation error: " + message + "."
		});
	},
 
	_handleGeolocationResponse: function (pos) {
		var lat = pos.coords.latitude,
		    lng = pos.coords.longitude,
		    latlng = new L.LatLng(lat, lng),
 
		    latAccuracy = 180 * pos.coords.accuracy / 40075017,
		    lngAccuracy = latAccuracy / Math.cos(L.LatLng.DEG_TO_RAD * lat),
 
		    sw = new L.LatLng(lat - latAccuracy, lng - lngAccuracy),
		    ne = new L.LatLng(lat + latAccuracy, lng + lngAccuracy),
		    bounds = new L.LatLngBounds(sw, ne),
 
		    options = this._locationOptions;
 
		if (options.setView) {
			var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
			this.setView(latlng, zoom);
		}
 
		var event = L.extend({
			latlng: latlng,
			bounds: bounds
		}, pos.coords);
 
		this.fire('locationfound', event);
	}
});