首页 文章

将Lat / Lng值推送到我的Google Maps API并将标记移动到事件的该位置

提问于
浏览
1

我创建了一个脚本,允许用户单击'Detect my location'按钮,一旦使用HTML5 Geolocation点击,将获得lat / lng值并在页面上显示 . 我正在使用本网站的geolocation.js - http://better-geolocation-api.googlecode.com

我有一个已设置的Google Map - 我想改变它,所以当点击'检测我的位置'按钮时,它会自动将lat / lng值发送到此并相应地移动标记 .

<!DOCTYPE html>
<html>
<head>
    <title>Google Maps Drag &amp; 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 + '
' + $('#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 + "
" + $('#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>

1 回答

  • 2

    首先,将 marker 变量设为全局变量,以便在onload匿名回调函数之外访问它 .

    然后就做:

    function alertMyPosition(position) {
        $('#geo').html(position.timestamp + ": " + position.coords.latitude + ", " + position.coords.longitude + "
    " + $('#geo').html()); marker.setPosition({lat: position.coords.latitude, lng: position.coords.longitude}); }

相关问题