I do not paint Google Map on the Web

2

I am trying to use the API of Google Maps so that I can paint a map according to the coordinates that happened to it, I do it with the method geolocation of HTML5 , but nothing appears on the web. I have tried the parameters that come by default in the Google documentation and it does not work either. The code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Tu Aplicación del Tiempo</title>
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <link rel="stylesheet" href="css/style.css">
</head>
<body>
  <div class="container">
    <h1>El Tiempo</h1>
    <h2 id="messageShow">Geolocalizando tú posición, espera un momento...</h2>

    <div id="map">
    </div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap"></script>
<script src="js/app.js"></script>
</html>

//JavaScript

(function Prueba(){

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(getCoords, errorFound)
} else {
   alert("Upgrade your browser");
}

function errorFound(error) {
   alert("Error: " + error.code ); 
}

function getCoords(position) {
 var lat = position.coords.latitude;
 var lon = position.coords.longitude;

 console.log("Your position is: " + lat + "," + lon);

 $.getJSON({
    url: WEATHER_API_URL + "&lat=" + lat + "&lon=" + lon
  }, getCurrentWeather, initMap)
}

function initMap(){
var map;

map = new google.maps.Map(document.getElementById('map'), {
   center: {lat: lat, lng: lon},
   zoom: 8
 });
}
})();

There is a call AJAX to a API of the time that does not have to do with the question, but there if the geolocation works. The console gives me the following error: InvalidValueError: initMap is not a function

I hope you help me with this error. Thank you. Juan.

    
asked by Juan 15.08.2016 в 13:24
source

2 answers

1

This is a problem with the scope (or scope ) of variables and functions. When doing:

(function Prueba(){
    ....

    function initMap(){
    ....
    }

})();

the initMap function lives within the Test function and can not be called out of it (at least not simply doing initMap() which is what will be attempted with the callback ).

The solution would be to either remove the Prueba() share:

//(function Prueba(){

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(getCoords,  
} else {
   alert("Upgrade your browser");
}

function errorFound(error) {
   alert("Error: " + error.code ); 
}

function getCoords(position) {
 var lat = position.coords.latitude;
 var lon = position.coords.longitude;

 console.log("Your position is: " + lat + "," + lon);

 $.getJSON({
    url: WEATHER_API_URL + "&lat=" + lat + "&lon=" + lon
  }, getCurrentWeather, initMap)
}

function initMap(){
var map;

map = new google.maps.Map(document.getElementById('map'), {
   center: {lat: lat, lng: lon},
   zoom: 8
 });
}
//})();

or if for any reason you need that code to be executed in that way, at least move initMap out:

(function Prueba(){

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(getCoords, errorFound)
} else {
   alert("Upgrade your browser");
}

function errorFound(error) {
   alert("Error: " + error.code ); 
}

function getCoords(position) {
 var lat = position.coords.latitude;
 var lon = position.coords.longitude;

 console.log("Your position is: " + lat + "," + lon);

 $.getJSON({
    url: WEATHER_API_URL + "&lat=" + lat + "&lon=" + lon
  }, getCurrentWeather, initMap)
}


})();

function initMap(){
var map;

map = new google.maps.Map(document.getElementById('map'), {
   center: {lat: lat, lng: lon},
   zoom: 8
 });
}

Update from the comment- " OK, but if I do this I get the error that: lat, and lon are not defined, in both cases ".

That's a question of the scope of the variables and how initMap is called. Right now the variables lat and lon are defined locally in getCoords and are not available outside it, if you want to use them in another function you should make them global or pass them to the other functions. Also, you have to call initMap when the Google Maps API is loaded (with callback ) and also call when the JSON is loaded in getCoords ; even if they were global, it could be the case that the callback was called before and they were still undefined.

Change app.js to this:

var lat, lon;

function getCoordinates() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(getCoords, errorFound)
    } else {
       alert("Upgrade your browser");
    }
}

function errorFound(error) {
   alert("Error: " + error.code ); 
}

function getCoords(position) {
 lat = position.coords.latitude;
 lon = position.coords.longitude;

 console.log("Your position is: " + lat + "," + lon);

 $.getJSON({
    url: "map.php" + "?lat=" + lat + "&lon=" + lon
  }, getCurrentWeather, initMap);

  initMap();
}

function initMap(){
   var map;
   console.log(lat + "," + lon);
   map = new google.maps.Map(document.getElementById('map'), {
     center: {lat: lat, lng: lon},
     zoom: 8
   });
}

and I have this HTML:

<body>
  <div class="container">
    <h1>El Tiempo</h1>
    <h2 id="messageShow">Geolocalizando tú posición, espera un momento...</h2>

    <div id="map" style="width:200px; height:200px">
    </div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="js/app.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=TU_API_KEY&callback=getCoordinates"></script>
    
answered by 15.08.2016 / 17:25
source
1

How about, try to check some things if you think you are using Maps correctly.

  

1.- If you use google chrome, it does not allow you to score points since you need a certificate for it. Try using another browser as   Firefox

     

2.- Try always to go from less to more as soon as you use an api.

     

3.- Always check what the console says, to know more details of the problem

<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 8
  });
}

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
        async defer></script>
  </body>
</html>
    
answered by 15.08.2016 в 15:00