私はGoogle Map 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>