Stephen
Stephen

Reputation: 537

Google Maps API: Place marker at current map location

How would I go about placing a marker at the current centre of the map using a button click?

Currently I have it so a marker is placed at a specific latitude and longitude (53.41291, -8.243889999999965). But I would like it to be placed at the current centre of the map.

Here's my Javascript as it is:

var latlng = new google.maps.LatLng(53.41291, -8.243889999999965) ;

var infowindow = new google.maps.InfoWindow({
  content: 'This is a place'
  });

function addmarker(latilongi) {
    var marker = new google.maps.Marker({
        position: latilongi,
        title: 'new marker',
        draggable: true,
        map: map
    });
    map.setCenter(marker.getPosition())
    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
  });
}


$('#addPoint').on('click', function() {
    addmarker(latlng)
})

Upvotes: 0

Views: 160

Answers (1)

duncan
duncan

Reputation: 31912

You want to centre your marker on the map's centre?

function addmarker() {
    var marker = new google.maps.Marker({
        position: map.getCenter(),
        title: 'new marker',
        draggable: true,
        map: map
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
  });
}

If you also want to be able to click on the map, and add a marker (and presumably then following the same rule, centre the map on that position)...

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

Upvotes: 1

Related Questions