Using the Google Maps API for a given Longitude and Latitude

0

I'm creating a website, I want it in it when a user puts an input into the longitude and latitude, google maps returns the exact location, I've seen several tutorials talking about google maps api but I can not.

Here's the code I'm using:

<script src="http://maps.google.com/maps?file=api&v=2ampkey=AIzaSyAaj8LTfKJ6tgN1ulSEUYsD9Xqs4wnurMs"type="text/javascript"></script>
<div id="gmap" style="width: 100%"></div>
<script type="text/javascript">
//<![CDATA[
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("gmap"));
map.setCenter(new GLatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>), 13);
}
}
//]]>
</script>
    
asked by anonymous 12.02.2016 / 04:39

3 answers

2

It is no longer necessary to make a request to the server with latitude and longitude. You can get the values (with the same Javascript) of the new location and only update the map through the function panTo() .

(function() {

  /**
   * Inicializando o mapa.
   * DOCS: https://developers.google.com/maps/documentation/javascript/examples/map-simple
   */
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: {
      lat: -23.6815315,
      lng: -46.8754965
    }
  });

  
  /**
   * Atualiza a localização com base nos valores inseridos nos inputs, quando o usuário
   * pressionar o botão 'buscar'.
   
   * Usando a função 'panTo' ao invés de 'setCenter' para fazer uma
   * transição mais amigável (animada) entre a localização antigaa e a nova.
   */
  document.querySelector('button').addEventListener('click', function() {

    var lat = document.getElementById('lat').value,
        lon = document.getElementById('lon').value;

    var point = new google.maps.LatLng(lat, lon);
    map.panTo(point);

  }, false);

})();
#map {
  margin-top: 8px;
  height: 260px;
  width: 100%
}
<script src='https://maps.googleapis.com/maps/api/js'></script>

<input id='lat' placeholder='Latitude'  />
<input id='lon' placeholder='Longitude' />
<button>Buscar</button>

<div id='map'></div>
    
12.02.2016 / 23:56
1

Visit the Google maps API for complete examples.

Here's a example that does exactly what it asks for, so that it works. which you replace in the URL YOUR_API_KEY with your KEY API, if you do not already have one you can create here .

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Reverse Geocoding</title>
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

    </style>
    <style>
      #floating-panel {
        position: absolute;
        top: 5px;
        left: 50%;
        margin-left: -180px;
        width: 350px;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
      }
      #latlng {
        width: 225px;
      }
    </style>
  </head>
  <body>
    <div id="floating-panel">
      <input id="latlng" type="text" value="40.714224,-73.961452">
      <input id="submit" type="button" value="Reverse Geocode">
    </div>
    <div id="map"></div>
    <script>
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: {lat: 40.731, lng: -73.997}
  });
  var geocoder = new google.maps.Geocoder;
  var infowindow = new google.maps.InfoWindow;

  document.getElementById('submit').addEventListener('click', function() {
    geocodeLatLng(geocoder, map, infowindow);
  });
}

function geocodeLatLng(geocoder, map, infowindow) {
  var input = document.getElementById('latlng').value;
  var latlngStr = input.split(',', 2);
  var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
  geocoder.geocode({'location': latlng}, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      if (results[1]) {
        map.setZoom(11);
        var marker = new google.maps.Marker({
          position: latlng,
          map: map
        });
        infowindow.setContent(results[1].formatted_address);
        infowindow.open(map, marker);
      } else {
        window.alert('No results found');
      }
    } else {
      window.alert('Geocoder failed due to: ' + status);
    }
  });
}

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap"
        async defer></script>
  </body>
</html>
    
12.02.2016 / 23:50
1

I do not know if this is the problem or if it has already been solved, but try to do what follows. In the API management console, enable the following APIs:

  • Google Maps JavaScript API
  • Google Maps Geocoding API
24.08.2016 / 19:41