Google Maps – Autocomplete

<!DOCTYPE html>
<html>
  <head>
    <title>Place Autocomplete</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=places&v=weekly"
      defer
    ></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <style type="text/css">
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
       #map {
         height: 500px;
         width: 800px;
         border-radius: 15px;
         margin: 50px auto;
       }

    </style>
    <script>
      // This example requires the Places library. Include the libraries=places
      // parameter when you first load the API. For example:
      // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
      function initMap() {
        const map = new google.maps.Map(document.getElementById("map"), {
          center: { lat: -33.8688, lng: 151.2195 },
          zoom: 13,
        });
        const input = document.getElementById("pac-input");
        const autocomplete = new google.maps.places.Autocomplete(input);
        // Bind the map's bounds (viewport) property to the autocomplete object,
        // so that the autocomplete requests use the current map bounds for the
        // bounds option in the request.
        autocomplete.bindTo("bounds", map);
        // Set the data fields to return when the user selects a place.
        autocomplete.setFields([
          "address_components",
          "geometry",
          "icon",
          "name",
        ]);

        autocomplete.setTypes(["address"]);

        const infowindow = new google.maps.InfoWindow();

        const marker = new google.maps.Marker({
          map,
          anchorPoint: new google.maps.Point(0, -29),
        });
        autocomplete.addListener("place_changed", () => {

          infowindow.close();
          marker.setVisible(false);
          const place = autocomplete.getPlace();

          if (!place.geometry) {
            // User entered the name of a Place that was not suggested and
            // pressed the Enter key, or the Place Details request failed.
            window.alert(
              "No details available for input: '" + place.name + "'"
            );
            return;
          }

          const coords = place.geometry.location
          document.getElementById("textLatitude").innerHTML = coords.lat();
          document.getElementById("textLongitude").innerHTML = coords.lng();

          // 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.
          }
          marker.setPosition(place.geometry.location);
          marker.setVisible(true);
          let 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.open(map, marker);
        });

      }
    </script>
  </head>
  <body>

    <div class="pac-card" id="pac-card">
      <input
      class="form-control  col-md-6"
      style="margin:auto; width:800px;"
      id="pac-input" type="text"
      placeholder="Enter a location" />
    </div>
    <div id="map"></div>

    <center>
      <h2>Coordenadas</h2>
      <h3>Latitude</h3>
      <p id="textLatitude">Latitude</p>
      <h3>Longitude</h3>
      <p id="textLongitude">Longitude</p>
    </center>

  </body>
</html>

API Key

https://console.developers.google.com/apis/credentials

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *