简体   繁体   中英

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)
})

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM