我能够获得自己的经度和纬度并将它们保存到变量:
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
我只是不确定如何将它们传递给在屏幕上显示地图初始位置的代码:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
我需要将 myLat 和 myLong 输入该行:
center: new google.maps.LatLng(-34.397, 150.644)
我只是不知道该怎么做。谁能指出我正确的方向?
编辑:根据以下请求添加完整代码
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=YOUR KEY HERE&sensor=true"></script>
<script type="text/javascript">
//MAP
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
//GEOLOCATION
var onSuccess = function(position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n');
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
map.setCenter(new google.maps.LatLng(myLat, myLong))
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
</script>
和 HTML:
<body onload="initialize()">
<div id="map_canvas" style="width:300px; height:400px;"></div>
</body
>