网络编程 
首页 > 网络编程 > 浏览文章

在AngularJS中如何使用谷歌地图把当前位置显示出来

(编辑:jimmy 日期: 2025/12/25 浏览:3 次 )

--在html5中,为我们提供了navigator.geolocation.getCurrentPosition(f1, f2)函数,f1是定位成功调用的函数,f2是定位失败调用的函数,而且会把当前的地理位置信息作为实参传递给f1和f2函数。f1函数调用谷歌地图的API即可。

如何展示呢?

--需要一个提示信息和展示地图的一个区域。

页面上,大致是这样:

<map-geo-location height="400" width="600"></map-geo-location>
<script src="/UploadFiles/2021-04-02/angular.js">

Directive部分如下:

(function(){
var mapGeoLocation = ['$window', function($window){
var template = '<p><span id="status">正在查找地址...</span></p>' + '<br /><div id="map"></div>',
mapContainer = null,
status = null;
function link(scope, elem, attrs){
//以Angular的方式获取Angular元素
status = angular.element(document.getElementById('status'));
mapContainer = angular.element(document.getElementById('map'));
mapContainer.attr('style', 'height:' + scope.height + 'px;width:' + scope.width + 'px');
$window.navigator.geolocation.getCurrentPosition(mapLocation, geoError);
}
//定位成功时调用
function mapLocation(pos){
status.html('found your location! Longitude: ' + pos.coords.longitude + ' Latitude: ' + pos.coords.latitude);
var latlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
var optons = {
zoom:15,
center: latlng,
myTypeCOntrol: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(mapContainer[0], options);
var marker = new google.maps.Markser({
position: latlng,
map: map, 
title: "Your location"
});
}
//定位失败时调用
function geoError(error){
status.html('failed lookup ' + error.message);
}
return {
restrict: 'EA', //默认
scope:{
height: '@',
width:'@'
},
link: link,
template: template
}
}];
angular.module('direcitveModule',[])
.direcitve('mapGeoLocation', mapGeoLocation);
}());

以上所述是小编给大家介绍的在AngularJS中如何使用谷歌地图把当前位置显示出来的相关知识,希望对大家有所帮助。

上一篇:javascript产生随机数方法汇总
下一篇:理解JavaScript表单的基础知识
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。