angularjsHow can I use AngularJS to implement a location search feature?
AngularJS can be used to implement a location search feature by using the HTML5 Geolocation API. The following example code will get the current user's location and display it on the page:
<!DOCTYPE html>
<html>
<head>
<title>Location Search</title>
</head>
<body>
<div ng-app="locationSearch" ng-controller="locationCtrl">
<h1>Location Search</h1>
<p>{{location}}</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
angular.module('locationSearch', [])
.controller('locationCtrl', function($scope) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$scope.$apply(function() {
$scope.location = "Latitude: " + position.coords.latitude +
" Longitude: " + position.coords.longitude;
});
});
}
});
</script>
</body>
</html>
Output example
Latitude: 37.78825 Longitude: -122.4324
The code consists of the following parts:
- An HTML page with the
ng-app
directive and ang-controller
directive to define the AngularJS application and controller. - A script tag to include the AngularJS library.
- An AngularJS application and controller to get the current user's location and display it on the page.
Helpful links
More of Angularjs
- How can I become an Angular expert from a beginner level?
- How can I create an editable AngularJS application?
- How can I use the Yandex Map API with AngularJS?
- How can I use Angular to zoom in and out of a div?
- How do I install Yarn using Angular?
- How do I use AngularJS to zoom in on an image?
- How do I use Angular Zone to run my code?
- How do I use Angular to zip files?
- How do I use Angular Zone to detect and run Angular change detection?
- How do I copy an element in AngularJS?
See more codes...