[英]Google Maps API: Use my own coords in JavaScript API
我可以获取自己的经度和纬度并将其保存到vars中:
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
>
只是
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));
之所以不起作用,是因为以下功能
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。
您只需在google.maps.LatLng中将myLat和myLong作为构造函数参数传递即可。 因此您的代码应如下所示:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.