我已经查看了很多有关此问题的其他报告,但我无法找到获取用户位置的解决方案。
这是我的代码:
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true'>
</script>
<script>
// prepare variables
var main = document.getElementById('main');
// async XHR request
var xhReq = new XMLHttpRequest();
xhReq.open('GET','../data/data.json', true);
xhReq.onload = function (e) {
if ((xhReq.readyState === 4) && (xhReq.status === 200)) {
// prepare external data
var data = JSON.parse(xhReq.responseText);
// prepare map
var map;
// var bounds = new google.maps.LatLngBounds();
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(54.6867151,25.2803843)
};
map = new google.maps.Map(main,mapOptions);
// add all data to the map
for(i=0;i<data.length;i++){
// loc = new google.maps.LatLng(data[i].lat,data[i].lng);
// bounds.extend(loc);
window['marker'+i] = new google.maps.Marker({
position: new google.maps.LatLng(data[i].lat,data[i].lng),
map: map,
title: data[i].name,
articles: data[i].articles
}
);
// add onClick function
google.maps.event.addListener(window['marker'+i], 'click', function() {
// magic should be here
var data = this.articles;
var list = document.getElementById('list');
var main = document.getElementById('main');
list.innerHTML = '';
list.style="width:25%;";
for(i=0;i<data.length;i++){
list.innerHTML += '<a href="' + data[i].url + '" target="_blank"><div class="listImg" style="background-image:url(' + data[i].img + ');"><\/div><span class="topic">(' + data[i].topic + ')<\/span> <h1>' + data[i].name + ' <\/h1><span class="date">(' + data[i].date + ')<\/span><\/a>';
};
});
};
// recenter + rezoom
// map.fitBounds(bounds);
// map.panToBounds(bounds);
};
};
xhReq.send(null);
</script>
它将地图中心设置为代码中的精确坐标 感谢您的支持。
英语不是我的第一语言,所以请原谅任何错误。
答案 0 :(得分:1)
获取用户位置是大多数现代浏览器支持的浏览器功能。但是,您仍需要测试在代码中获取位置的能力。
if (navigator.geolocation) { // test for presence of location feature
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
console.log('user denied request for position');
});
} else {
console.log('no geolocation support');
}