Anjyr Anjyr - 10 months ago 66
Javascript Question

Marker on the center of map after drag

I implement google map on my website. User can drag the marker and get coordinates. It's working fine but requirement is that when user drag marker, after drag marker should come on the center of the map window or if user drag map, then for this case marker also come to the center of map window.

I have the following code which is working for only drag marker on the map,
but I don't know where to add the function or code that move the marker on the center of map window after drag.

That code is written below:

google.maps.event.addListener(myMarker, 'dragend', function (evt) {
document.getElementById('dragStatus').innerHTML = '<p> Current Lat: ' + + ' Current Lng: ' + evt.latLng.lng().toFixed(4) + '</p>';
var point = marker.getPosition();

google.maps.event.addListener(myMarker, 'dragstart', function (evt) {

Answer Source

This is (I think) an easier solution... Or I didn't quite get what you want to achieve.

//Dragable Marker In Google Map....

var center = new google.maps.LatLng(-33.013803, -71.551498);

var map = new google.maps.Map(document.getElementById('mapBox'), {
    zoom: 18,
    center: center,
    mapTypeId: google.maps.MapTypeId.HYBRID

var myMarker = new google.maps.Marker({
    position: center,
    draggable: true,
    map: map

google.maps.event.addListener(myMarker, 'dragend', function () {
    map.setCenter(this.getPosition()); // Set map center to marker position
    updatePosition(this.getPosition().lat(), this.getPosition().lng()); // update position display

google.maps.event.addListener(map, 'dragend', function () {
    myMarker.setPosition(this.getCenter()); // set marker position to map center
    updatePosition(this.getCenter().lat(), this.getCenter().lng()); // update position display

function updatePosition(lat, lng) {
    document.getElementById('dragStatus').innerHTML = '<p> Current Lat: ' + lat.toFixed(4) + ' Current Lng: ' + lng.toFixed(4) + '</p>';

JSFiddle demo