大家好我有以下代码:
var map;
var infowindow;
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(initialize);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function initialize(position) {
var pyrmont = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 500,
types: ['restaurant']
};
...
基本上,如果设置Long / Lat坐标,我可以让地图工作得很好,但我希望通过获取用户位置来传递这些。使用上面的代码,地图显示在我的手机上,但出现以下错误:
TypeError: 'undefined' is not an object (evaluating 'position.coords.latitude')
但在桌面上我没有地图和以下错误:
Uncaught TypeError: Cannot read property 'latitude' of undefined
任何帮助都会很棒我是Javascript和这些AP的新手
答案 0 :(得分:4)
稍后在您的代码中,在您http://markhaynes.me/mwp/addloc.html的页面上,您正在呼叫google.maps.event.addDomListener(window, 'load', initialize);
这会导致Google调用initialize()函数,但它会将事件对象作为position
参数传递,而不是您期望的位置对象。
答案 1 :(得分:1)
这不是地理位置API的问题。这是一个地理定位的JSFIDDLE:http://jsfiddle.net/w4nvZ/3/
此处还有API的文档和示例:http://www.w3schools.com/html/html5_geolocation.asp
Google甚至有一个使用JavaScript Google Maps API进行地理定位的示例:https://google-developers.appspot.com/maps/documentation/javascript/examples/map-geolocation
var map;
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);