Using the Google Maps API for certain Longitude and Latitude

Asked

Viewed 2,529 times

0

I am creating a site, I want in it when a user put in an input to longitude and latitude, google maps returns to exact location, I’ve seen several tutorials talking about google maps api but I can’t.

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>
  • 1

    Even if it doesn’t work, it’s important to show the code you’ve already built so we can help.

  • 2

    Have you read the Google Maps API documentation (https://developers.google.com/maps/) there explains everything and with examples

  • Edit your question with the code, as you yourself said you have tried.

  • 1

    If you found an answer to this question it would be great if you put it here, as an answer below.

3 answers

2


It is not necessary to make a request to the server with latitude and longitude. You can take the values (with 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>

  • It is giving an error, I even took the example of Docs, this giving this error: It was not possible to display an element of Google Maps on this page. Contact the site administrator. If you are the site administrator, check the Javascript console or the following page to perform the troubleshooting: http://g.co/mapsJSApiErrors

  • The snippet ran smoothly, http://prntscr.com/a2vsbl

  • this error does not seem to have anything to do with the code I posted or with google maps, where it is trying to integrate the code?

  • I think it’s the domain. Because google blocks the sites with Free Download (.esy.es) I was using this free Download (or free host) to test how the site would look etc.. Now I’m going to buy a . com domain and it’s going to be all right, I think.. If it does, I put your question as correct :)

1

Visit the Google maps API for full examples.

You got a example that does exactly what you ask, so it works you have to replace in the URL YOUR_API_KEY by your API KEY, if you don’t 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>
  • I tried to use this code here, and gave it this: Could not display a Google Maps element on this page. Contact the site administrator. If you are the site administrator, check the Javascript console or the following page to perform the troubleshooting: http://g.co/mapsJSApiErrors

  • which of the errors appeared?

  • The map simply didn’t appear! He gave a written Alert that I quoted, and nothing else.. But my question has already been answered, thank you!

1

I don’t know if this is the problem or if you already solved it, but try to do what follows. In the API management console, activate the following Apis:

  • Google Maps Javascript API
  • Google Maps Geocoding API
  • I did a long time ago, but thank you so much for taking the time to try and help me :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.