Skip to content

Instantly share code, notes, and snippets.

@nidhhoggr
Created March 8, 2016 19:53
Show Gist options
  • Save nidhhoggr/047c40f4fc0bea27fd7c to your computer and use it in GitHub Desktop.
Save nidhhoggr/047c40f4fc0bea27fd7c to your computer and use it in GitHub Desktop.
(function () {
'use strict';
angular
.module('com.module.core')
.service('MapService', function () {
var rad = function(x) { return x*Math.PI/180;}
var distHaversine = function(latLngBounds) {
var R = 6371; // earth's mean radius in km
var bounds = latLngBounds.toJSON();
var dLat = rad(bounds.east - bounds.west);
var dLong = rad(bounds.south - bounds.north);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(bounds.east)) * Math.cos(rad(bounds.west)) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d.toFixed(3);
}
var calculateZoomFromHaversineDist = function(dist) {
var zoom = 4;
if(dist < 1.25) {
zoom = 15;
} else if(dist < 2.5) {
zoom = 14;
} else if(dist < 5) {
zoom = 13;
} else if(dist < 10) {
zoom = 12;
} else if(dist < 20) {
zoom = 11;
} else if(dist < 40) {
zoom = 10;
} else if(dist < 80) {
zoom = 9;
} else if(dist < 160) {
zoom = 8;
} else if(dist < 320) {
zoom = 7;
} else if(dist < 640) {
zoom = 6;
} else if(dist < 1180) {
zoom = 6;
} else if(dist < 2360) {
zoom = 5;
}
return zoom;
}
this.fitToLatLngBounds = function(latLngBounds) {
this.map.panTo(latLngBounds.getCenter());
this.map.fitBounds(latLngBounds);
this.zoomFromLatLngBounds(latLngBounds);
}
this.zoomFromLatLngBounds = function(latLngBounds) {
var dist = distHaversine(latLngBounds);
console.log("Harvesine dist from bounds", dist);
var zoom = calculateZoomFromHaversineDist(dist);
console.log("Resulting zoom level from harvesine", zoom);
this.map.setZoom(zoom);
};
this.setMap = function(mapInstance) {
this.map = mapInstance;
};
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment