Warm tip: This article is reproduced from stackoverflow.com, please click
google-maps javascript google-maps-api-3

Unable to use google maps Markers, and issue with javascript Global variables

发布于 2020-03-29 21:01:23

I want to make a page where the user keeps entering latitude and longitude values, and these places are plotted on the map and route between these is gained.

Initially, i am trying to plot markers on the map by taking latitude and longitude values from the user.

My html is like this:

    <div>
            <label for = "lat">Enter Latitude</label>
            <input id="lat" type="text" name="lat">
            <label for = "lat">Enter Longitude</label>
            <input id="lng" type="text" name="lng">
            <button id ="submit">Submit</button>
        </div>
        <div id="map"></div>

My css is like this:

<style>
    /*Set the height explicitly.*/
    #map {
        height: 400px;
        width: 100%
    }
</style>

And i am using Google Map javascript like this.

<script src="https://maps.googleapis.com/maps/api/js?key=myAPIKey&callback=initMap" async defer></script>

And my script is like this:

        <script>        
            var map=0;
            function initMap(){
                    var pesCollege = {lat:12.9345, lng:77.5345};
                    map = new google.maps.Map(document.getElementById('map'), {
                        center:pesCollege,
                        zoom: 10
                    });
                    console.log("Inside initMap");
                    console.log(map);    //this is printing map properties
                    return map;
                    // var marker = new google.maps.Marker({position: pesCollege, map : map});
                   //This marker works if uncommented!
               }

                plot();                    

                function plot(){
                    console.log("inside plot function")
                    console.log(map);    //this is printing 0, i.e. global variable map is not 
                                         //loaded with map inside initMap
                    // var latlng = new google.maps.LatLng(latitude, longitude);
                    var pesCollege = {lat:12.9345, lng:77.5345};
                    var marker = new google.maps.Marker({position: pesCollege, map :map});  
                  //I want this marker to work.

                    // var marker = new google.maps.Marker({position: latlng,setMap: map}); 
                    console.log("Marker set")


                 }

If this works, then i think i can pass latitude and longitude values to plot the markers by adding event listener like this:

var button = document.getElementById('submit')  
        button.addEventListener("click", function(){
            var dict = {};
            var latitude = document.getElementById('lat').value;
            var longitude = document.getElementById('lng').value;
            x = parseInt(latitude);
            y = parseInt(longitude);
            dict['lat']=latitude;
            dict['lng']=longitude;
            var cdns = JSON.stringify(dict);
            // alert("hi");
            alert(cdns);    
            console.log(dict);
            console.log(cdns);
            plotPoint(x,y); //this is a similar funtion to plot() but i send l&l values, not sure if i can pass them like this.
            plot();     
        });

and my plotPoint(x,y) is like this

function plotPoint(latitude,longitude){
    var latlng = new google.maps.LatLng(latitude, longitude);
    var marker = new google.maps.Marker({position: latlng,map: map}); 
    console.log("Marker set")
}

I already read a lot of git answers but none resembled my problem. Any help would be greate. Thanks in advance.

Questioner
Chaitra D
Viewed
57
MrUpsidown 2020-01-31 18:44

I have reduced the code you provided to the minimum so that it plots a Marker when submitting the lat/lng pair.

You should be doing further checks though. The code, as it is, will fail if you don't provide a latitude and/or longitude and hit submit.

Here is a working code snippet. I have added comments, please read them.

var map;

function initMap() {

  // Default map location
  var pesCollege = {
    lat: 12.9345,
    lng: 77.5345
  };

  // Create the map and center on deault location
  map = new google.maps.Map(document.getElementById('map'), {
    center: pesCollege,
    zoom: 10
  });
  
  // Create a Marker at the default location
  var marker = new google.maps.Marker({
    position: pesCollege,
    map: map
  });

  var button = document.getElementById('submit');

  button.addEventListener("click", function() {

    // Get latitude and longitude values from inputs
    var latitude = document.getElementById('lat').value;
    var longitude = document.getElementById('lng').value;

    // Are you sure about that?
    // This will return an integer, ie. 12.3452 will become 12
    latitude = parseInt(latitude);
    longitude = parseInt(longitude);

    // Send the values
    plotPoint(latitude, longitude);
  });
}

function plotPoint(lat, lng) {

  // Create a LatLng with the given coordinates
  var pos = new google.maps.LatLng(lat, lng);

  // Create a Marker at the given coordinates
  var marker = new google.maps.Marker({
    position: pos,
    map: map
  });

  // Pan the map to see your added Marker
  map.panTo(pos);
}
#map {
  height: 400px;
  width: 100%
}
<div>
  <label for="lat">Enter Latitude</label>
  <input id="lat" type="text" name="lat">
  <label for="lat">Enter Longitude</label>
  <input id="lng" type="text" name="lng">
  <button id="submit">Submit</button>
</div>

<div id="map"></div>

<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>

To add a bit more info:

  • In the API call, you have added callback=initMap which will execute the initMap function once the API script has finished loading. All Google Maps related code should be initialized in this function as otherwise you might be calling Google Maps methods before it has finished loading which will error.

  • You should always refer to the official documentation for properties and methods.

  • You should watch your Javascript console for errors.