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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15417130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:43:04  来源:igfitidea点击:

How to get latitude and longitude from google maps v3 api?

javascriptgoogle-mapsgoogle-maps-api-3

提问by ehp

I am trying create a map using google maps v3 api. I have found the below code over internet and I want to show the latitude and logitude in map window instead of address.

我正在尝试使用 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);
        });

Please some one help me to get and show latitude and longitude. Thank you very much.

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

采纳答案by Rafe

Where you have

你有的地方

  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);

Change the infowindow line to read

将 infowindow 行更改为 read

  infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + place.geometry.location.lat() + ',' + place.geometry.location.lng());

回答by Roy M J

Much simpler solution will be :

更简单的解决方案是:

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);
  }
});

Cheers

干杯

回答by user2791641

Take a look at this code..

看看这个代码..

<!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>

回答by Ben Racicot

Looks like you might be looking for just regular geolocation stuff? Here's my snippett from a project to grab a user's lat/long

看起来您可能只是在寻找常规的地理定位内容?这是我从一个项目中获取用户纬度/经度的片段

trigger show_user_location(); to begin the geolocation API.

触发 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;

} 

回答by Akhil Ghatiki

When you want the lat and long of any part of the map,try adding the click listeners for the map not the marker. The code should be something like below:

当您需要地图任何部分的经纬度时,请尝试为地图添加点击侦听器而不是标记。代码应该如下所示:

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);
        });
        }
    });

This will display the lat and long of any location on the map using a info window.

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

回答by akolliy

I created a tiny component to illustrate with React. Although, it's the same API. I thought this might be helpful.

我创建了一个小组件来说明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,
};