Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidpp/7456506 to your computer and use it in GitHub Desktop.
Save davidpp/7456506 to your computer and use it in GitHub Desktop.
ExampleController = ($scope, LocationService) ->
LocationService.locate().then (position) ->
$scope.position = position
ExampleController.$inject = ["$scope", "LocationService"]
YourAngularApp.controller("ExampleController", ExampleController)
<div ng-controller="ExampleController">
<div class="well" ng-show="position">
<h1>{{position.address}}</h1>
<span>Within {{position.coords.accuracy}}m</span>
</div>
<div ng-hide="position">
<h1>Finding your position...</h1>
</div>
</div>
LocationService = ($q, $rootScope, ReverseGeolocationService) ->
locate = ->
defer = $q.defer()
navigator.geolocation.getCurrentPosition(
(position) ->
ReverseGeolocationService.findAddress(
position.coords.latitude,
position.coords.longitude
).then (address) ->
position = {coords: position.coords}
position.address = address
defer.resolve(position)
,
(error) ->
defer.reject(error)
)
defer.promise
{locate: locate}
LocationService.$inject = ["$q", "$rootScope", "ReverseGeolocationService"]
YourAngularApp.factory("LocationService", LocationService)
ReverseGeolocationService = ($q, $rootScope, $http) ->
url = (latitude, longitude) ->
"http://nominatim.openstreetmap.org/reverse?format=json&lat=#{latitude}&lon=#{longitude}&zoom=18&addressdetails=0"
findAddress = (latitude, longitude) ->
defer = $q.defer()
$http(method: 'GET', url: url(latitude, longitude))
.success (data) ->
defer.resolve(data.display_name)
.error (status) ->
defer.rejct(status)
defer.promise
{findAddress: findAddress}
ReverseGeolocationService.$inject = ["$q", "$rootScope", "$http"]
YourAngularApp.factory "ReverseGeolocationService", ReverseGeolocationService
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment