Rui*_*Rui 1 javascript api google-maps geolocation
所以我必须在我的页面上添加一个"中心"按钮,当点击时,地图将使用setCenter方法在引脚上居中.但是,在我单击我的按钮后,地图变为空白而不是显示中心.
这是我的代码.
如何解决问题?先感谢您!
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function init() {
var addButton = document.getElementById("setcenter");
addButton.onclick = handleSetCenterButtonClicked;
getMyLocation();
}
window.onload = init;
function getMyLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation);
} else {
alert("Oops, no geolocation support");
}
}
function displayLocation(position) {
showMap(position.coords);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById("location");
div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}
var map;
function showMap(coords) {
var googleLatAndLong = new google.maps.LatLng(coords.latitude, coords.longitude);
var mapOptions = {
zoom : 18,
center : googleLatAndLong,
mapTypeId : google.maps.MapTypeId.SATELLITE
};
var mapDiv = document.getElementById("map");
map = new google.maps.Map(mapDiv, mapOptions);
addMarker(googleLatAndLong);
}
var marker;
var markerArray = new Array();
function addMarker(latLong) {
var markerOptions = {
position : latLong,
map : map
};
marker = new google.maps.Marker(markerOptions);
markerArray.push(marker);
}
// this is my setCenter method function
function handleSetCenterButtonClicked(coords) {
var latLng = new google.maps.LatLng(coords.latitude, coords.lotitude);
map.setCenter(latLng);
}
// this is my setCenter method function
</script>
Run Code Online (Sandbox Code Playgroud)
问题在于你的功能(除了拼写错误):
function handleSetCenterButtonClicked(coords) {
var latLng = new google.maps.LatLng(coords.latitude, coords.lotitude);
map.setCenter(latLng);
}
Run Code Online (Sandbox Code Playgroud)
点击coords是类型MouseEvent,没有任何关于lat/lng的信息.这MouseEvent与google api不同.目前尚不清楚要设置哪个值为中心.打开页面的用户的位置?或者其他一些价值?
如果你想在他拖动后将中心定位到用户位置,你可以添加全局变量:
var yourPos;
Run Code Online (Sandbox Code Playgroud)
在函数showMap()中将其设置为已知值:
yourPos = googleLatAndLong;
Run Code Online (Sandbox Code Playgroud)
并在点击处理程序中使用它:
function handleSetCenterButtonClicked(coords) {
//var latLng = new google.maps.LatLng(coords.lat(), coords.lng());
//map.setCenter(latLng);
map.setCenter(yourPos);
}
Run Code Online (Sandbox Code Playgroud)
除此之外,如果用户不想分享他的位置,则不会处理案件.
| 归档时间: |
|
| 查看次数: |
16238 次 |
| 最近记录: |