我可以获得自己的经度和纬度并将它们保存到变量中:
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
&GT;
答案 0 :(得分:3)
只是
var map;
function initialize() {
//...
}
initialize();
function initiate_geolocation() {
navigator.geolocation.getCurrentPosition(onSuccess);
}
function onSuccess(position){
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
map.setCenter(new google.maps.LatLng(myLat, myLong)); // edit this line
}
initiate_geolocation();
它不是map.setCenter(new LatLng(myLat, myLong));
而应该是map.setCenter(new google.maps.LatLng(myLat, myLong));
答案 1 :(得分:3)
这不起作用的原因是以下功能
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 LatLng(myLat, myLong));
};
使用时
map.setCenter(new LatLng(myLat, myLong))
你必须使用
map.setCenter(new google.maps.LatLng(myLat, myLong))
LatLng对象将是未定义的。您需要使用的对象是google.maps.LatLng。
答案 2 :(得分:0)
您可以简单地将myLat和myLong作为构造函数参数传递给google.maps.LatLng。所以你的代码应该是这样的:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(myLat,myLong),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
}