原因是您没有为“updateMarkerPosition(latLng)”指定(即定义)“latLng”,例如 var latLng = "37.780145,-122.418435"(请注意,稍后您可能需要将此字符串坐标转换为实际数字)。还有几点需要注意:
- “geocodePosition”函数未定义。
- “updateMarkerPosition”函数并不完全正确,因此即使您将 lat lng 值传递给该函数(例如“updateMarkerPosition(-27.3959,153.0626)”,它也不会正确显示。这是因为没有属性“lat”和“lng”代表纬度。
- “updateMarkerPosition”函数不会更新地图或对地图做任何事情。
不确定这是否是您要查找的内容,但这是一个快速而肮脏的示例,谷歌地图会在加载时获取您当前的位置并显示您的位置坐标。然后,您可以在文本框中指定坐标(格式为:37.780145,-122.418435)并点击搜索。然后地图将更新并显示您输入的位置。
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style type="text/css">
#map-canvas {
height: 400px;
width: 500px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var posRounded = position.coords.latitude.toFixed(4) + "," + position.coords.longitude.toFixed(4);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'You are here: ' + posRounded
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
// Custom Function: Update Marker Position
function updateMarkerPosition() {
var latLng = document.getElementsByClassName('lat-lng')[0].value.replace(" ","").split(",");
var pos = new google.maps.LatLng(latLng[0], latLng[1]);
var posRounded = parseFloat(latLng[0]).toFixed(4) + "," + parseFloat(latLng[1]).toFixed(4);
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(latLng[0], latLng[1]),
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var infowindowOptions = {
map: map,
position: pos,
content: 'You are here: ' + posRounded
};
var markerOptions = {
map: map,
position: pos
}
infowindow = new google.maps.InfoWindow(infowindowOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<h2>Google Map</h2>
<div id="map-canvas"></div>
<div id="info" style="margin-top:20px;">
<input class="lat-lng" type="text" placeholder="Enter lat lng here..."/>
<button type="button" onclick="updateMarkerPosition()">Look it up!</button>
</div>
</body>
</html>