简体   繁体   中英

Need to get latitude and longitude from google map API

https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

I'm using the map which I got from above link. It works fine in my website. When I search for a place ,that location will be shown in map. I need to get its longitude and latitude and should be displayed in a textbox when I click on a place on Google map.

The code is shown below

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
.controls {
  margin-top: 10px;
  border: 1px solid transparent;
  border-radius: 2px 0 0 2px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  height: 32px;
  outline: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

#pac-input {
  background-color: #fff;
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
  margin-left: 12px;
  padding: 0 11px 0 13px;
  text-overflow: ellipsis;
  width: 300px;
}

#pac-input:focus {
  border-color: #4d90fe;
}

.pac-container {
  font-family: Roboto;
}

#type-selector {
  color: #fff;
  background-color: #4d90fe;
  padding: 5px 11px 0px 11px;
}

#type-selector label {
  font-family: Roboto;
  font-size: 13px;
  font-weight: 300;
}

    </style>
    <title>Places Searchbox</title>
    <style>
      #target {
        width: 345px;
      }
    </style>
  </head>
  <body>
    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
    <div id="map"></div>
    <script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.

function initAutocomplete() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -33.8688, lng: 151.2195},
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  // Create the search box and link it to the UI element.
  var input = document.getElementById('pac-input');
  var searchBox = new google.maps.places.SearchBox(input);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

  // Bias the SearchBox results towards current map's viewport.
  map.addListener('bounds_changed', function() {
    searchBox.setBounds(map.getBounds());
  });

  var markers = [];
  // [START region_getplaces]
  // 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);
  });
  // [END region_getplaces]
}


    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAkwr5rmzY9btU08sQlU9N0qfmo8YmE91Y&libraries=places&callback=initAutocomplete"
         async defer></script>
  </body>
</html>
places.forEach(function(place) {
console.log("lat: "+place.geometry.location.lat()+" lng: "+place.geometry.location.lng())
//etc

you would need to put an event listener on the map object, then get the coordinates of the click event when it happens:

map.addListener('click', function (locationdata) {
  document.getElementById("latitude").value =locationdata.latLng.lat();
  document.getElementById("longitude").value =locationdata.latLng.lng();
});

and adjust your html accordingly

You already have the location data at place collection, you can use loop . here is the simplest way to do this .

 for (var i = 0, place; place = places[i]; i++) {

      alert("latitude: "+place.geometry.location.lat()+" longitude: "+place.geometry.location.lng());


 });

if you want to add this in a array

var locationArray[];

for (var i = 0, place; place = places[i]; i++) {

      alert("latitude: "+place.geometry.location.lat()+" longitude: "+place.geometry.location.lng());

      locationArray[i]= places[i].geometry.location;

 });

here is the code example jsfiddle

Add a listener to each marker, use it to add that marker's position to the text box.

  // Create a marker for each place.
  var marker = new google.maps.Marker({
    map: map,
    icon: icon,
    title: place.name,
    position: place.geometry.location
  });
  google.maps.event.addListener(marker,'click',function(evt) {
      document.getElementById('coordinates').value = marker.getPosition().toUrlValue(6);
  });
  markers.push(marker);

proof of concept fiddle

code snippet:

 // This example adds a search box to a map, using the Google Place Autocomplete // feature. People can enter geographical searches. The search box will return a // pick list containing a mix of places and predicted search terms. // clicked marker coordinates will be placed in the input text element with id="coordinates" function initAutocomplete() { var map = new google.maps.Map(document.getElementById('map'), { center: { lat: -33.8688, lng: 151.2195 }, zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }); // Create the search box and link it to the UI element. var input = document.getElementById('pac-input'); var searchBox = new google.maps.places.SearchBox(input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); // Bias the SearchBox results towards current map's viewport. map.addListener('bounds_changed', function() { searchBox.setBounds(map.getBounds()); }); var markers = []; // [START region_getplaces] // 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. var marker = new google.maps.Marker({ map: map, icon: icon, title: place.name, position: place.geometry.location }); google.maps.event.addListener(marker, 'click', function(evt) { document.getElementById('coordinates').value = marker.getPosition().toUrlValue(6); }); markers.push(marker); if (place.geometry.viewport) { // Only geocodes have viewport. bounds.union(place.geometry.viewport); } else { bounds.extend(place.geometry.location); } }); map.fitBounds(bounds); }); // [END region_getplaces] } google.maps.event.addDomListener(window, 'load', initAutocomplete);
 html, body { height: 100%; margin: 0; padding: 0; } #map { height: 100%; } .controls { margin-top: 10px; border: 1px solid transparent; border-radius: 2px 0 0 2px; box-sizing: border-box; -moz-box-sizing: border-box; height: 32px; outline: none; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); } #pac-input { background-color: #fff; font-family: Roboto; font-size: 15px; font-weight: 300; margin-left: 12px; padding: 0 11px 0 13px; text-overflow: ellipsis; width: 300px; } #pac-input:focus { border-color: #4d90fe; } .pac-container { font-family: Roboto; } #type-selector { color: #fff; background-color: #4d90fe; padding: 5px 11px 0px 11px; } #type-selector label { font-family: Roboto; font-size: 13px; font-weight: 300; } #target { width: 345px; }
 <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script> <input id="coordinates" type="text" size="30" /> <input id="pac-input" class="controls" type="text" placeholder="Search Box"> <div id="map"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM