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 use Angular to zoom in and out of a div?
- How can I become an Angular expert from a beginner level?
- How do I use Angular to zip files?
- How do I use Angular Zone to detect and run Angular change detection?
- How can I use AngularJS to create a zone in my software development project?
- How do I use Angular with YAML?
- How do AngularJS and Angular differ?
- How do I create a yes/no dialog box using Angular?
- How can I prevent XSS attacks when using AngularJS?
- How can I use Zone.js with Angular to detect and act upon asynchronous events?
See more codes...