如何从谷歌地图v3 api获取纬度和经度?

14

我试图使用Google Maps V3 API创建地图。我在互联网上找到了下面的代码,并希望在地图窗口中显示纬度和经度,而不是地址。

<script>
      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(-33.8688, 151.2195),
          zoom: 13,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById('map_canvas'),
          mapOptions);

        var input = document.getElementById('searchTextField');
        var autocomplete = new google.maps.places.Autocomplete(input);

        autocomplete.bindTo('bounds', map);

        var infowindow = new google.maps.InfoWindow();
        var marker = new google.maps.Marker({
          map: map
        });

        google.maps.event.addListener(autocomplete, 'place_changed', function() {
          infowindow.close();
          marker.setVisible(false);
          input.className = '';
          var place = autocomplete.getPlace();
          if (!place.geometry) {
            // Inform the user that the place was not found and return.
            input.className = 'notfound';
            return;
          }

          // If the place has a geometry, then present it on a map.
          if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
          } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);  // Why 17? Because it looks good.
          }
          var image = {
            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(35, 35)
          };
          marker.setIcon(image);
          marker.setPosition(place.geometry.location);
          marker.setVisible(true);

          var address = '';
          if (place.address_components) {
            address = [
              (place.address_components[0] && place.address_components[0].short_name || ''),
              (place.address_components[1] && place.address_components[1].short_name || ''),
              (place.address_components[2] && place.address_components[2].short_name || '')
            ].join(' ');
          }

          infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
          infowindow.open(map, marker);
        });

请有人帮我获取并显示纬度和经度。非常感谢。

6个回答

12

当你拥有的时候

  var address = '';
  if (place.address_components) {
    address = [
      (place.address_components[0] && place.address_components[0].short_name || ''),
      (place.address_components[1] && place.address_components[1].short_name || ''),
      (place.address_components[2] && place.address_components[2].short_name || '')
    ].join(' ');
  }

  infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
  infowindow.open(map, marker);
改变信息窗口行以阅读
  infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + place.geometry.location.lat() + ',' + place.geometry.location.lng());

谢谢,它解决了我的问题。但我还有一个问题是是否可能仅显示纬度、经度和地址,而不显示地图。如果可能的话,请告诉我如何做。 - ehp
1
请阅读使用条款。看起来您可以在没有地图的情况下显示地点内容,但必须显示“由Google提供动力”的标志。如果您没有地图,不确定需要坐标做什么。在这种情况下,您可能不想使用Google Maps API v3,只需使用Places API即可。 - geocodezip
我只是想了解它。我将在地图上展示它。 顺便说一下,我还想显示城市名称和州的缩写。 例如,对于新泽西州普林斯顿市,我想显示为princeton,nj。 如何实现这一点?或者能否获取州名缩写? - ehp
1
https://developers.google.com/maps/documentation/javascript/geocoding#ReverseGeocoding 可能会对你有所帮助。向下滚动一点,它会显示一些可能性。 - Rafe
@Rafe 我正在使用place.address_components[2].short_name来获取州的信息。对于一些城市,它可以正常工作,但不是所有城市都可以。例如,对于亚利桑那州,它会出现TypeError: place.address_components[2]未定义的错误。 如何处理这个错误? - ehp

10

更简单的解决方案将是:

var address = "New Delhi"
$.ajax({
  url:"http://maps.googleapis.com/maps/api/geocode/json?address="+address+"&sensor=false",
  type: "POST",
  success:function(res){
     console.log(res.results[0].geometry.location.lat);
     console.log(res.results[0].geometry.location.lng);
  }
});

加油!


这个怎么不会触发“同源”域问题呢? - Francisco Presencia
@FranciscoPresencia:它不会引发跨域问题..:).. 你可以简单地运行它并查看..:) - Roy M J
很确定那违反了服务条款。为什么不使用更用户友好的自动完成呢? - Walf
@Walf: 结账:请查看https://developers.google.com/terms/,Google唯一的限制是请求数量的限制。 如果我们每天想要有10,000个请求,那么我们可以选择付费选项。 - Roy M J

7

请看这段代码...

<!DOCTYPE html>
<html>
<head>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
    <script>
        function initialize() {
        var address = 'Kolkata';
            geocoder = new google.maps.Geocoder();
            geocoder.geocode({
            'address': address
            }, function(results, status) {      
                var lat=document.getElementById("lat").innerHTML=results[0].geometry.location.lat();    
                var lng=document.getElementById("lng").innerHTML=results[0].geometry.location.lng();        
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>
<body>
    <p id="lat"></p> 
    <p id="lng"></p> 
</body>
</html>

geometry.location.lat() 完美的答案。 - TarangP

2

看起来你可能只是在寻找普通的地理定位信息?以下是我从一个项目中提取的代码片段,用于获取用户的经纬度。

使用trigger show_user_location(); 来启动地理定位API。

function show_user_location(){ 

    navigator.geolocation.getCurrentPosition(display_user_location, error_response); 
} 
function display_user_location(user_position){ 
    var lat = user_position.coords.latitude; 
    var lon = user_position.coords.longitude; 

// once we get here make that AJAX query
// #loc.value="<p>Your latitude is: "+lat+", your longitude is: "+lon+"</p>"+ "<p><a href='http://maps.google.com/?q="+lat+","+lon+"'>View your location on Google Maps</a></p>";

    // I often put the lat/lon in a hidden form for later retrieval here.
    // value = document.getElementById('lat').value;
    // value = document.getElementById('lat').value;

    document.getElementById("lat").value = lat;
    document.getElementById("long").value = lon;

} 

1
当您想获取地图上任何部分的纬度和经度时,请尝试为地图添加点击侦听器而不是标记。代码应该类似于以下内容:
var infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);

    service.getDetails({
        placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4'
    },function(place,status){
        if(status === google.maps.places.PlacesServiceStatus.OK)
        {
            var marker = new google.maps.Marker({
                map:map,
                position: place.geometry.location

            });

        google.maps.event.addListener(map, 'click', function(e) {
          infowindow.setContent('<div>'+'Longitute'+'<strong>' + e.latLng.lng() + '</strong><br>' +
            'Latitude:'+'<strong>' + e.latLng.lat()+'</strong>'  + '</div>');
          infowindow.open(map, this);
        });
        }
    });

这将使用信息窗口在地图上显示任何位置的纬度和经度。

1

我创建了一个小组件,用React来说明。虽然它使用相同的API,但我认为这可能会有所帮助。

import React, { useState } from 'react';

import PropTypes from 'prop-types';
import { GoogleApiWrapper } from 'google-maps-react';

const SearchLocation = ({ google }) => {
  const [inputData, setInputData] = useState('');

  const handleChange = ({ target: { value } }) => {
    if (value) {
      setInputData(value);
      const autoCompleteService = new google.maps.places.AutocompleteService();
      autoCompleteService.getPlacePredictions(
        { input: value },
        (predictions, status) => {
           if (status === google.maps.places.PlacesServiceStatus.OK) {
              // update prediction, so that user can click on the predicted address
              const updatePredictions = (predictions) => {};
              // or get the coordinate of one prediction
              if (predictions.length > 0) {
                 geoCodeLocation(predictions[0]);
              }
           }
        }
      );
    }
  };

  const geoCodeLocation = (suggestion) => {
    const placeId = suggestion.place_id;
    const GeoCoder = new google.maps.Geocoder();
    GeoCoder.geocode({ placeId }, (response) => {
      const lattitude = response[0].geometry.location.lat();
      const longitude = response[0].geometry.location.lng();
      const coordinates = [longitude, lattitude];
      // save coordinate and suggestion
      const selectLocation = ({ coordinates, suggestion }) => {};
    });
  };

  return (
    <div>
        <input
          type="text"
          name="searchLocation"
          placeholder="Enter your address..."
          className="text-field"
          onChange={handleChange}
        />
      {/* handle suggestion */}
   </div>
  );
};

export default GoogleApiWrapper({
  apiKey: process.env.GOOGLE_API_KEY,
  v: '3'
})(SearchLocation);

SearchLocation.defaultProps = {};

SearchLocation.propTypes = {
  google: PropTypes.shape({}).isRequired,
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接