我创建了一个脚本,允许用户点击“检测我的位置”。按钮&一旦使用HTML5 Geolocation点击将获得lat / lng值&在页面上显示。我正在使用此网站上的geolocation.js - http://better-geolocation-api.googlecode.com
我有一个已设置的Google地图 - 我想改变这一点,以便在“检测我的位置'单击按钮,它将自动将lat / lng值发送到此&相应地移动标记。
<!DOCTYPE html>
<html>
<head>
<title>Google Maps Drag & Drop to Lat/Lng</title>
<style type="text/css">
#map { height: 500px; border: 1px solid #000; }
#geo { height: 200px; overflow: auto; }
</style>
</head>
<body>
<button id="getPositionButton">Get</button>
<div id="geo"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script src="http://code.google.com/apis/gears/gears_init.js"></script>
<script src="http://better-geolocation-api.googlecode.com/files/geolocation.js"></script>
<script src="jquery.geolocation.js"></script>
<script>
function success(position) {
$('#geo').html(position.coords.latitude + ', ' + position.coords.longitude + '<br />' + $('#geo').html());
}
$(function() {
function alertMyPosition(position) {
alert("Your position is " + position.coords.latitude + ", " + position.coords.longitude);
$('#geo').html(position.timestamp + ": " + position.coords.latitude + ", " + position.coords.longitude + "<br />" + $('#geo').html());
}
function noLocation(error) {
$('#geo').text("No location info available. Error code: " + error.code);
}
$('#getPositionButton').bind('click', function() {
$.geolocation.get({win: alertMyPosition, fail: noLocation});
});
});
</script>
<div id="map"></div>
<p>Initial Lat/Lng : 52.5879, -1.9824</p>
<script type="text/javascript">
window.onload = function() {
var latlng = new google.maps.LatLng(52.5879, -1.9824);
var map = new google.maps.Map(document.getElementById('map'), {
center: latlng,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Set lat/lon values for this property',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function(a) {
console.log(a);
var div = document.createElement('div');
div.innerHTML = a.latLng.lat().toFixed(4) + ', ' + a.latLng.lng().toFixed(4);
document.getElementsByTagName('body')[0].appendChild(div);
});
};
</script>
答案 0 :(得分:2)
首先,将marker
变量设为全局变量,以便在onload匿名回调函数之外访问它。
然后就这样做:
function alertMyPosition(position) {
$('#geo').html(position.timestamp + ": " + position.coords.latitude + ", " + position.coords.longitude + "<br />" + $('#geo').html());
marker.setPosition({lat: position.coords.latitude, lng: position.coords.longitude});
}