Add marker to Google Map on Click

前端 未结 6 1904
有刺的猬
有刺的猬 2020-12-12 09:50

I\'m surprisingly struggling to find a very simple example of how to add a marker(s) to a Google Map when a user left clicks on the map.

I have looked around for the

相关标签:
6条回答
  • 2020-12-12 10:22

    Currently the method to add the listener to the map would be

    map.addListener('click', function(e) {
        placeMarker(e.latLng, map);
    });
    

    And not

    google.maps.event.addListener(map, 'click', function(e) {
        placeMarker(e.latLng, map);
    });
    

    Reference

    0 讨论(0)
  • 2020-12-12 10:22
    1. First declare the marker:
    this.marker = new google.maps.Marker({
       position: new google.maps.LatLng(12.924640523603115,77.61965398949724),
       map: map
    });
    
    1. Call the method to plot the marker on click:
    this.placeMarker(coordinates, this.map);
    
    1. Define the function:
    placeMarker(location, map) {
        var marker = new google.maps.Marker({
            position: location,
            map: map
        });
        this.markersArray.push(marker);
    }
    
    0 讨论(0)
  • 2020-12-12 10:26

    @Chaibi Alaa, To make the user able to add only once, and move the marker; You can set the marker on first click and then just change the position on subsequent clicks.

    var marker;
    
    google.maps.event.addListener(map, 'click', function(event) {
       placeMarker(event.latLng);
    });
    
    
    function placeMarker(location) {
    
        if (marker == null)
        {
              marker = new google.maps.Marker({
                 position: location,
                 map: map
              }); 
        } 
        else 
        {
            marker.setPosition(location); 
        } 
    }
    
    0 讨论(0)
  • 2020-12-12 10:34

    In 2017, the solution is:

    map.addListener('click', function(e) {
        placeMarker(e.latLng, map);
    });
    
    function placeMarker(position, map) {
        var marker = new google.maps.Marker({
            position: position,
            map: map
        });
        map.panTo(position);
    }
    
    0 讨论(0)
  • 2020-12-12 10:39

    After much further research, i managed to find a solution.

    google.maps.event.addListener(map, 'click', function(event) {
       placeMarker(event.latLng);
    });
    
    function placeMarker(location) {
        var marker = new google.maps.Marker({
            position: location, 
            map: map
        });
    }
    
    0 讨论(0)
  • 2020-12-12 10:47

    This is actually a documented feature, and can be found here

    // This event listener calls addMarker() when the map is clicked.
      google.maps.event.addListener(map, 'click', function(e) {
        placeMarker(e.latLng, map);
      });
    
      function placeMarker(position, map) {
        var marker = new google.maps.Marker({
          position: position,
          map: map
        });  
        map.panTo(position);
      }
    
    0 讨论(0)
提交回复
热议问题