使用getElementById时,lat和lng不显示

时间:2012-08-25 22:51:26

标签: javascript google-maps geolocation

我按地址获得经纬度。一切都运作良好,我得到地图显示没有任何问题,但我想显示海拔和经度。

这是我的代码,我正在初始化

function codeAddress() {
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                draggable: true,
            });

        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
        google.maps.event.addListener(marker, 'click', function() {
            document.getElementById('lat').value = results[0].geometry.location.lat();
            document.getElementById('lng').value = results[0].geometry.location.lng();
        });
    });
}

以下是用法:

<div id="mapholder"></div>
            </p>
            <div id="map_canvas"></div>
            <div id="info"></div>
            <div>
                <input id="address" type="textbox" value="הזן כתובת">
                <input type="button" value="מצא את מיקומך" onclick="codeAddress()"><br>
                <input type="button" value="מצא קופונים באזורך" onclick="showPositionCoupons(32.105892, 35.198483)"><br>
                Latitude: <input type="text" id="lat"><br>
                Longitude: <input type="text" id="lng"><br>
            </div>

1 个答案:

答案 0 :(得分:0)

好吧,发现那个效果很好的代码

function updateCoordinates(latlng)
{
  if(latlng) 
  {
    document.getElementById('lat').value = latlng.lat();
    document.getElementById('lng').value = latlng.lng();
  }
}

function codeAddress() {
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            updateCoordinates(results[0].geometry.location);
            if (marker) marker.setMap(null);
            marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                draggable: true
            });

            google.maps.event.addListener(marker, "dragend", function() {
                updateCoordinates(marker.getPosition());
            });

        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}