I am trying to access data from a method within a service which returns coordinates which I use to make an HTTP requests. I added my Leaflet code inside of my controller so I can access that lat,lng coordinates to make an API request to another API. Everything is working. The problem is when I try to pass this data to the controller it does not read the property "L.Control.Search". I also attempted to write an array and access it within the controller and it returned undefined.
app.service('mapService', (function($http,$q) {
//Coordinates
var fmCoordinates = {};
//Function to Request markets
var requestMarkets = function(lat,lng){
var defer = $q.defer();
var dataFromHttp = {};
var options = {
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://someurl?lat=" + lat + "&lng=" + lng
};
$http(options).then(function(result) {
dataFromHttp = result.data;
defer.resolve(dataFromHttp);
}, function(error){
defer.reject(error);
});
return defer.promise;
};
L.Control.Search = L.Control.extend({
_getLocation: function(key) { //extract latlng from _recordsCache
var latLong = this._recordsCache[key];
console.log("This is latlong:\n"+Object.keys(latLong));
fmCoordinates.lat = latLong.lat;
fmCoordinates.lng = latLong.lng;
console.log(fmCoordinates.lat,fmCoordinates.lng || "Nothing yet!");
var promise = requestMarkets(fmCoordinates.lat,fmCoordinates.lng);
promise.then(function(greeting) {
for(var property in greeting.results) {
console.log(property + "=" + greeting.results[property]);
};
console.log('Success: ' + greeting.results);
}, function(reason) {
console.log('Failed: ' + reason);
});
if( this._recordsCache.hasOwnProperty(key) )
return latLong;//then after use .loc attribute
else
return false;
},
L.Map.addInitHook(function () {
if (this.options.searchControl) {
this.searchControl = L.control.search(this.options.searchControl);
this.addControl(this.searchControl);
}
});
L.control.search = function (options) {
return new L.Control.Search(options);
};
}));
I think your promise code is off slightly. Try changing it to the following. Right now you're returning before the promise has been resolved.
var requestMarkets = function(lat,lng){
var defer = $q.defer();
var dataFromHttp = {};
var options = {
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://someurl?lat=" + lat + "&lng=" + lng
};
return $http(options).then(function(result) {
dataFromHttp = result.data;
defer.resolve(dataFromHttp);
return defer.promise;
}, function(error){
defer.reject(error);
return defer.promise;
});
};
Also in one place you have l.Control.Search and L.control.search in another.