This repository has been archived by the owner on Jun 4, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
geocoder-service.js
78 lines (73 loc) · 1.75 KB
/
geocoder-service.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
(function(angular){
'use strict';
angular.module('geocoder-service', [])
.factory('geocoderService', [
'$document',
'$window',
'$q',
function(
$document,
$window,
$q
) {
var isloading = false,
finishedLoading = false,
callbacks = [],
geocoder;
$window.__initMaps = function() {
finishedLoading = true;
geocoder = new $window.google.maps.Geocoder();
for (var x = 0; x < callbacks.length; ++x) {
callbacks[x].resolve();
}
delete $window.__initMaps;
};
var geocodeAddress = function(address) {
var callback = function(address, defer) {
geocoder.geocode({address: address}, function(results, status){
if (status === $window.google.maps.GeocoderStatus.OK && results.length > 0) {
defer.resolve(results);
} else {
defer.reject();
}
});
};
var defer = $q.defer();
if (!finishedLoading) {
var d = $q.defer();
callbacks.push(d);
d.promise.then(function(){
callback(address, defer);
});
loadGeocoder();
} else {
callback(address, defer);
}
return defer.promise;
};
var loadGeocoder = function() {
if (isloading) {
return;
}
isloading = true;
var document = $document[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&callback=__initMaps';
document.body.appendChild(script);
};
var obj = {};
obj.getLatLong = function(address) {
return obj.getLocations(address).then(function(results){
if (results.length > 0) {
return results[0].geometry.location;
}
return null;
});
};
obj.getLocations = function(address) {
return geocodeAddress(address);
};
return obj;
}]);
})(angular);