web-dev-qa-db-fra.com

Comment obtenir la latitude et la longitude de google maps v3 api?

J'essaie de créer une carte à l'aide de Google Maps Api v3. J'ai trouvé le code ci-dessous sur Internet et je souhaite afficher la latitude et la logitude dans la fenêtre de la carte au lieu de l'adresse.

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

S'il vous plaît, aidez-moi à obtenir et à montrer la latitude et la longitude. Merci beaucoup.

10
ehp

Où vous avez

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

Changer la ligne d’infowindow pour lire

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

Une solution beaucoup plus simple sera: 

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

À votre santé

9
Roy M J

Jetez un oeil à ce 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>
7
user2791641

On dirait que vous êtes à la recherche de trucs de géolocalisation réguliers? Voici l'extrait d'un projet pour récupérer le lat/long d'un utilisateur

déclencheur afficher l'emplacement de l'utilisateur (); pour commencer l'API de géolocalisation.

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;

} 
2
TR3B

Lorsque vous souhaitez que les lat et long d'une partie de la carte, essayez d'ajouter les écouteurs de clic pour la carte, pas le marqueur. Le code devrait être quelque chose comme ci-dessous:

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

Cela affichera les lat et long de n’importe quel emplacement sur la carte en utilisant une fenêtre d’information.

1
Akhil Ghatiki