How can I get a single marker to update it's position as the user moves?


I'm showing a map with a "Track my Position" button. It starts marking the user's position, but leaves a trail of markers as the user moves. How can I get a single marker to update it's position as the user moves?

<script type="text/javascript"> $( document ).bind( "mobileinit", function() { $.mobile.allowCrossDomainPages = true; }); </script> <script src="../../jquery.mobile.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js? key=AIzaSyCvtEfhi11SeoL1Osfo8St53JRkasYnTRw&sensor=true"></script> <script src="../../cordova-2.7.0.js"></script> <script type="text/javascript"> var map; var image = "../../bbimages/cycling.png"; $(document).on('pageshow', '#fenlandmap', function(){ $(document).on('click', '#”btnInit”', function(){ navigator.geolocation.watchPosition(onMapSuccess, onMapFailure, {enableHighAccuracy:true,timeout:20000}); }); var latlng = new google.maps.LatLng(51.183244, -115.585399); var myOptions = { zoom: 15, streetViewControl: false, center: latlng, mapTypeId: google.maps.MapTypeId.HYBRID }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var kmlUrl = 'http://www.sites.google.com/site/skyrokml/kml/FenlandTrail.kml'; var kmlOptions = { suppressInfoWindows: false, preserveViewport: true, map: map }; var kmlLayer = new google.maps.KmlLayer(kmlUrl, kmlOptions); }); function onMapSuccess(pos) { map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)); var marker = new google.maps.Marker({ position: map.getCenter(), icon: image, map: map, title: 'Click to zoom' }); } function onMapFailure() { alert('You must have an internet connection to view the maps'); } </script> </head> <body> <div data-role="page" style="width:100%;height:100%;" id="fenlandmap"> <div data-role="content" style="width:100%;height:100%;" id="map_content"> <div id="map_canvas" style="width:100%; height:448px"></div> </div><!-- /content --> <div data-role="footer" data-position="fixed" id="footer" align="center"> <a href="../bbteasyfenlandloop.html" data-role="button" data-direction="reverse" data-transition="slide" data-icon="arrow-l">Back</a> <a href="../../index.html" data-role="button" data-transition="turn" data-direction="reverse" data-icon="home">Home</a> <button id=”btnInit” data-icon="star">Track my Position</button> </div> </div> <!-- /page --> </body>


Move the marker to the global scope. Outside of any function do this:

var marker = null;

Then you have two options:


move the marker if it has already been created.

if (marker == null) { marker = new google.maps.Marker({ position: map.getCenter(), icon: image, map: map, title: 'Click to zoom' }); } else { marker.setPosition(map.getCenter()); } </li> </ul>

<a href="http://www.geocodezip.com/v3_SO_updateMarkerPosn.html" rel="nofollow">working example</a>


destroy it and recreate it at the new location.

if (marker && marker.setMap) { marker.setMap(null); } marker = new google.maps.Marker({ position: map.getCenter(), icon: image, map: map, title: 'Click to zoom' }); </li> </ul>

<a href="http://www.geocodezip.com/v3_SO_updateMarkerPosn1.html" rel="nofollow">working example</a>


The following approach is suggested by me

<em>1)User clicks on botton 2)Marker is placed on map 3)User drag the marker and place it where it wants</em>

<strong>Now if the user wants to change its place again he will not click on any button just he will drag the marker at its new position</strong>

<html> <head> <script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script> <script type="text/javascript"> var lat, lng; var latlng = new google.maps.LatLng(18.5236, 73.8478); function initialize() { var myoptions = { center: latlng, zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"), myoptions); function addmarker(latlng) { var marker = new google.maps.Marker({ position: latlng, title: 'new marker', draggable: true, map: map }); google.maps.event.addListener(marker, 'dragend', function (evt) { document.getElementById('current').innerHTML='Latitude : ' + evt.latLng.lat().toFixed(5) + ' Longitude : ' + evt.latLng.lng().toFixed(5); lat = evt.latLng.lat().toFixed(5); // here you will always get latitude lng = evt.latLng.lng().toFixed(5); // here you will always get longitude }); google.maps.event.addListener(marker, 'dragstart', function (evt) { }); map.setCenter(marker.position); marker.setMap(map); } $('#btnaddmarker').on('click', function () { addmarker(latlng) var mapBtn = document.getElementById('btnaddmarker'); mapBtn.disabled = true; }) } google.maps.event.addDomListener(window, 'load', initialize); </script> <script type="text/javascript"> window.onload = function () { initialize(); } </script> </head> <body> <div class="welcome" style="width: 1200px; height:800px; margin: 0px 50px 0px 50px;"> <div> <button id="btnaddmarker" class="btn btn-primary" style="">add marker</button> <div id="current" style="float:right">Nothing yet...</div> </div> <div> <div id="googleMap" style="width: 100%; height: 500px; float: left; margin-left: -7px;"></div> </div> </div> </body> </html>

<strong>You will get the current user latitude and longitude at the right side using the above code</strong>


  • google maps v3: clearing a circle made from polylines off the map
  • How to use google Maps?
  • Close open InfoBubble when open a new (gMap v3)
  • handle click event in gmappanel extJS
  • What is causing gray space on a Google Map using v3 API?
  • Convert google maps polyline to html canvas line [closed]
  • How to add values in google map v3
  • Remove commas between google places types
  • trying to get location from address using google api v3
  • Does pouchdb leave deleted tombstones like couchdb does?
  • How to integrate Geodjango with Google Maps API 3?
  • How do I make a hybrid app in Windows 8?
  • How to curve a Polyline in react-google-maps?
  • Drawing a polygon over the entire map
  • Android Google Maps: Polygon or shape that hides entire map
  • Python-3 Request parameter encoding error
  • TypeError: Main.login is not a function
  • python struct.pack(): pack multiple datas in a list or a tuple
  • Get highlight text in current window and send it in a popup
  • How to click on a link that has a certain content in puppeteer?
  • Pointer to a logger class provide for all other classes? [duplicate]
  • Send the string to its hex equivalent
  • How to remove the dot in to_char if the number is an integer
  • Python: Split a String Field into 3 Separate Fields using Lambda
  • how do you obtain the address of an instance after overriding the __str__ method in python
  • Main Thread Checker: UI API called on a background thread iOS 11 Xcode 9 GM Seed
  • C function strchr - How to calculate the position of the character?
  • Getting Latitude Longitude from GoogleMaps in TWebBrowser
  • Google map in top corner left
  • quiver not drawing arrows just lots of blue, matlab
  • Update Google Maps traffic layer without page reloading
  • Does Mobilefirst provide a provision to access web services directly?
  • Parse a date string in a specific locale (not timezone!)
  • Seeking advice on Jetty HttpClient Hang
  • How to handle AllServersUnavailable Exception
  • Google cloud sdk not working when python points python3
  • 0x202A in filename: Why?
  • using HTMLImports.whenReady not working in chrome
  • Android Heatmap on canvas or ImageView
  • Python/Django TangoWithDjango Models and Databases