【问题标题】:Get latitude and longitude from search box从搜索框中获取经纬度
【发布时间】:2016-03-28 10:23:49
【问题描述】:

我知道很多线程都在讨论这个问题,但我的代码仍然不起作用。

我正在使用谷歌地方搜索框 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 错误:Uncaught ReferenceError: map is not defined。请提供一个Minimal, Complete, Tested and Readable example 来证明您的问题。和Uncaught TypeError: Cannot read property 'value' of null 在这一行var input = document.getElementById('alamat');(不在提供的 HTML 中)。
  • ok。抱歉。我已经更新了描述。

标签: javascript php google-maps


【解决方案1】:

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

如果是这样试试:

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

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

这是你想要达到的目标吗?

【讨论】:

  • 是的,它是一个文本框。但我也已经试过了。但它也没有用。哈哈。我是不是把代码放错地方了?
  • 看起来不像。您希望它在地图更改时更新,因此您需要它位于侦听器中。如果你做console.log(places.geometry.location.lat());,你会得到什么?我想它实际上是一个字符串值?
  • #x 是文本框还是文本区域?
  • 文本框。我已经更新了描述。我没有“api 密钥”。重要吗?
  • 还有一个错误:“TypeError: Cannot read property 'location' of undefined”
【解决方案2】:

我已经解决了问题。

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

places.forEach(function (place)) 内部 希望这会有所帮助。

【讨论】:

    【解决方案3】:

    它将地址转换为纬度和经度,并在地图中显示带有标记的地址。您只需添加地图 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>

    【讨论】:

      【解决方案4】:
      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

      【讨论】:

        猜你喜欢
        • 2017-11-20
        • 2014-01-21
        • 1970-01-01
        • 2013-01-16
        • 2014-08-29
        • 1970-01-01
        • 2020-11-07
        • 2010-12-02
        • 2019-11-05
        相关资源
        最近更新 更多