我是谷歌地图 API 的新手。我知道这可能是一个简单的。代码按需要工作,但我无法让标记最初显示在地图上。标记正在等待点击事件显示标记。首次加载地图时需要在地图上显示初始标记,以便可以拖动它。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" charset="utf-8" src="libs/jq.ui.min.js"></script>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places,visualization&sensor=false"></script>
<script>
var initialLocation;
var map;
var marker;
var latlon;
var lat;
var lon;
//---------------------------------------------------
getLocation();
//---------------------------------------------------
function getLocation()
{
if (navigator.geolocation)
{
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(initialize,showError,
{enableHighAccuracy:true,timeout:timeoutVal,maximumAge:0}
);
lat = position.coords.latitude;
lon = position.coords.longitude;
}
}
//---------------------------------------------------
function initialize() {
var myOptions={
center:latlon,
zoom:15,
zoomControl:true,
zoomControlOptions: {
style:google.maps.ZoomControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
myListener = google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
google.maps.event.removeListener(myListener);
});
google.maps.event.addListener(map, 'drag', function(event) {
placeMarker(event.latLng);
google.maps.event.removeListener(myListener);
});
// Try W3C Geolocation (Preferred)
if(navigator.geolocation) {
// browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
showError;
});
}
function placeMarker(location) {
marker = new google.maps.Marker({
position: location,
icon:'map_icon3.png',
animation:google.maps.Animation.DROP,
map: map,
draggable: true
});
marker.setMap(map);
map.setCenter(location);
var markerPosition = marker.getPosition();
populateInputs(markerPosition);
google.maps.event.addListener(marker, "drag", function (mEvent) {
populateInputs(mEvent.latLng);
});
}
function populateInputs(pos) {
document.getElementById("t1").value=pos.lat()
document.getElementById("t2").value=pos.lng();
}
}
//-------------------------------------------------------------------
function showError(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
x.innerHTML="User Denied Geolocation"
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML="Location Data Unavailable"
break;
case error.TIMEOUT:
x.innerHTML="Request Timed Out"
break;
case error.UNKNOWN_ERROR:
x.innerHTML="Unknown Error Occurred"
break;
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 500px; height: 500px"></div>
<input type="text" id="t1" name="t1" />
<input type="text" id="t2" name="t2" />
</body>
</html>