How to Move Marker Smoothly on Google Map using JavaScript


Google Maps API provides an easy way to display maps on the website. You can point the location using a marker on Google Map and be show the text/HTML on info window. The map functionality can be extended in a various way and you can implement the Google Map on the web page as per your requirement.

If you want to extend Google map functionality in a user-friendly way, the animated marker can be a useful feature. In this tutorial, we will show you how to move marker smoothly on Google map using Google Maps JavaScript API.

This example script displays a map with a marker using Google Maps JavaScript API. On clicking on the Google Map, the marker moves smoothly and the marker position is changed.

Google Maps JavaScript API

Google Maps JavaScript API is used to create the map, so load this API first. You need to specify an API key in API URL for using the Google Maps JavaScript API.

<script src=""></script>

See this step-by-step instruction to get your own API key – How to Get Google Maps JavaScript API Key

JavaScript Code

The initialize() function creates a Google Map with a marker. The transition() and moveMarker() are used to move marker smoothly on click on the Google map.

var position = [40.748774, -73.985763];

function initialize() { 
    var latlng = new google.maps.LatLng(position[0], position[1]);
    var myOptions = {
        zoom: 16,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    map = new google.maps.Map(document.getElementById("mapCanvas"), myOptions);

    marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: "Latitude:"+position[0]+" | Longitude:"+position[1]

    google.maps.event.addListener(map, 'click', function(event) {
        var result = [, event.latLng.lng()];

//Load google map
google.maps.event.addDomListener(window, 'load', initialize);

var numDeltas = 100;
var delay = 10; //milliseconds
var i = 0;
var deltaLat;
var deltaLng;

function transition(result){
    i = 0;
    deltaLat = (result[0] - position[0])/numDeltas;
    deltaLng = (result[1] - position[1])/numDeltas;

function moveMarker(){
    position[0] += deltaLat;
    position[1] += deltaLng;
    var latlng = new google.maps.LatLng(position[0], position[1]);
    marker.setTitle("Latitude:"+position[0]+" | Longitude:"+position[1]);
        setTimeout(moveMarker, delay);

HTML Code:

The following HTML defines an area to display the Google Map. The selector ID (mapCanvas) need to be specified in the initialize() function.

<div id="mapCanvas"></div>

CSS Code

The following CSS sets the height and width of the Google Map div.

    width: 100%;
    height: 400px;

Related Articles

Comments 0