从搜索框获取纬度和经度

问题描述 投票:-1回答:3

我知道很多线程讨论这个但我的代码仍然不起作用。我正在使用google place searchBox API。

我的代码:

function initMap(){
            var map = new google.maps.Map(document.getElementById('peta'), {
                center: {lat: -34.397, lng: 150.644},
                zoom: 16
            });
            var infoWindow = new google.maps.InfoWindow({map: map});

            // Try HTML5 geolocation.
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    var pos = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
                    };

                    infoWindow.setPosition(pos);
                    infoWindow.setContent('Your Location.');
                    map.setCenter(pos);
                }, function() {
                    handleLocationError(true, infoWindow, map.getCenter());
                });
            } else {
                // Browser doesn't support Geolocation
                handleLocationError(false, infoWindow, map.getCenter());
            }

            var input = document.getElementById('alamat');
            var searchBox = new google.maps.places.SearchBox(input);

            // Bias the SearchBox results towards current map's viewport.
            map.addListener('bounds_changed', function() {
                searchBox.setBounds(map.getBounds());
            });
            var markers = [];
            // Listen for the event fired when the user selects a prediction and retrieve
            // more details for that place.
            searchBox.addListener('places_changed', function() {
                var places = searchBox.getPlaces();

                if (places.length == 0) {
                    return;
                }

                // Clear out the old markers.
                markers.forEach(function(marker) {
                    marker.setMap(null);
                });
                markers = [];

                // For each place, get the icon, name and location.
                var bounds = new google.maps.LatLngBounds();
                places.forEach(function(place) {
                    var icon = {
                        url: place.icon,
                        size: new google.maps.Size(71, 71),
                        origin: new google.maps.Point(0, 0),
                        anchor: new google.maps.Point(17, 34),
                        scaledSize: new google.maps.Size(25, 25)
                    };

                    // Create a marker for each place.
                    markers.push(new google.maps.Marker({
                        map: map,
                        icon: icon,
                        title: place.name,
                        position: place.geometry.location

                    }));

                    if (place.geometry.viewport) {
                        // Only geocodes have viewport.
                        bounds.union(place.geometry.viewport);
                    } else {
                        bounds.extend(place.geometry.location);
                    }
                });
                map.fitBounds(bounds);
                document.getElementById('x').innerHTML(places.geometry.location.lat());
     });
}

链接脚本:

<script  async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&libraries=places"></script>

HTML:

<div id="peta" style="width:500px;height:380px;"></div>
<input type="text" id="x" readonly="readonly" name="x">

我把document.getElementById放在我的文本框上,但它仍然没有显示纬度。我应该把这段代码放在哪里? 在其他线程中: var location= places.geometry.location; var lat = location.lat(); 但它也不行。如果我重复这个问题,我很抱歉。谢谢。

javascript php google-maps
3个回答
1
投票

你的元素#x是输入文本框吗?

如果是这样尝试:

 document.getElementById('x').value = places.geometry.location.lat();

这会将纬度添加到输入文本框的值。

这是你想要实现的目标吗?


1
投票

我已经解决了这个问题。

正如@Dammeul所说,我放置了 document.getElementById('x').value = place.geometry.location.lat();

places.forEach(function (place))内部希望这有用。


0
投票

它会将地址转换为纬度和经度,并使用标记在地图中显示地址。您刚刚添加了地图API密钥

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">


var geocoder;
  var map;
  function initMap() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(23.684994, 90.35633099999995);
    var mapOptions = {
      zoom: 8,
      center: latlng
    }
    map = new google.maps.Map(document.getElementById('map'), mapOptions);
  }

  function codeAddress() {
    var address = document.getElementById('address').value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == 'OK') {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
  }
  
 function showResult(result) {
    document.getElementById('latitude').value = result.geometry.location.lat();
    document.getElementById('longitude').value = result.geometry.location.lng();
	
	
}

function getLatitudeLongitude(callback, address) {
   
    address = address || 'Dhaka,Bangladesh';
   
    var geocoder = new google.maps.Geocoder();
    if (geocoder) {
        geocoder.geocode({
            'address': address
        }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                callback(results[0]);
            }
        });
    }
}

var button = document.getElementById('show');
button.addEventListener("click", function () {
    var address = document.getElementById('address').value;
    getLatitudeLongitude(showResult, address)
});

</script>
<!doctype html>
<html>
<head>
 
<style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 400px;
		width: 800px;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
</head>
<body onload="initMap()">
<div>
   <div id="map" style="width: 320px; height: 480px;"></div>
  <div>
    <input id="address" type="textbox" value="">
    <input type="button" id="show" value="Show" onclick="codeAddress()">
  </div>
  <div>
        <p>Latitude:
            <input type="text" id="latitude" readonly />
        </p>
        <p>Longitude:
            <input type="text" id="longitude" readonly />
        </p>
    </div>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.