从搜索框获取纬度和经度

时间:2016-03-28 10:23:49

标签: javascript php google-maps

我知道很多线程都在讨论这个问题,但我的代码仍然无效。 我正在使用google放置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();
但它也不行。如果我重复这个问题,我很抱歉。谢谢。

4 个答案:

答案 0 :(得分:1)

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

若是,请尝试:

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

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

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

答案 1 :(得分:1)

我已经解决了这个问题。

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

<{1>} places.forEach(function (place))内 希望这有用。

答案 2 :(得分: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>

答案 3 :(得分:0)

const { GoogleMap, LoadScript } = require("../../");
const ScriptLoaded = require("../../docs/ScriptLoaded").default;

const mapContainerStyle = {
  height: "400px",
  width: "800px"
};

const center = {
  lat: 38.685,
  lng: -115.234
};

const onLoad = ref => this.searchBox = ref;

const onPlacesChanged = () => {
    
      x = this.searchBox.getPlaces()
      console.log(x[0]["geometry"]["location"].lat())
    
    
    }
    

<ScriptLoaded>
  <GoogleMap
    id="searchbox-example"
    mapContainerStyle={mapContainerStyle}
    zoom={2.5}
    center={center}
  >
    <StandaloneSearchBox
      onLoad={onLoad}
      onPlacesChanged={
        onPlacesChanged
      }
    >
      <input
        type="text"
        placeholder="Customized your placeholder"
        style={{
          boxSizing: `border-box`,
          border: `1px solid transparent`,
          width: `240px`,
          height: `32px`,
          padding: `0 12px`,
          borderRadius: `3px`,
          boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
          fontSize: `14px`,
          outline: `none`,
          textOverflow: `ellipses`,
          position: "absolute",
          left: "50%",
          marginLeft: "-120px"
        }}
      />
    </StandaloneSearchBox>
  </GoogleMap>
</ScriptLoaded>

您好,我尝试了一下,而且效果很好,我已经很久了,我正在使用react + searchboxAPI,请随时跟进,这里是文档,我意识到您不能做x [“ geometry”] [“ location”]。lat(),相反,您需要遍历返回的每个地方,以对其进行测试,我做了 console.log(x [0] [“ geometry”] [“ location”]。lat())仅用于获取第一个结果。您可以使用js map函数或使用for循环遍历20个数组。欢呼

https://react-google-maps-api-docs.netlify.app/#!/StandaloneSearchBox/1