Leaflet moving marker
HTML
<link rel="stylesheet" href="https://unpkg.com/leaflet@0.7.7/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@0.7.7/dist/leaflet-src.js"></script>
<div id="map"></div>
CSS
#map {
height: 400px;
}
JavaScript
// Create the map
var map = L.map('map').setView([-31.4, -64.183], 12);
// Set up the OSM layer
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
// add a marker in the given location
var lat = -31.4;
var lng = -64.183;
var marker = L.marker([lat, lng]).addTo(map);
var radius = 15000; // in meters.
var circle = L.circle([lat, lng], radius).addTo(map);
// add a layer and add points
var myLayer = L.geoJson().addTo(map);
// geojsonFeature
var geojsonFeature = {
"type": "Feature",
"properties": {
"name": "Coors Field",
"amenity": "Baseball Stadium",
"popupContent": "This is where the Rockies play!"
},
"geometry": {
"type": "Point",
"coordinates": [-104.99404, 39.75621]
}
};
// put the marker
setTimeout(function() {
myLayer.addData(geojsonFeature);
}, 1000);
// update the marker
setTimeout(function() {
// clear layer
myLayer.clearLayers(); // inherited from LayerGroup
//myLayer.addData(geojsonFeature);
}, 3000);
// put the marker
setTimeout(function() {
myLayer.addData(geojsonFeature);
}, 5000);
// just fooling around
setInterval(function() {
lat = lat + ((Math.random() * 1) - 0.25) * 0.001;
lng = lng + ((Math.random() * 1) - 0.5) * 0.001;
var newLatLng = [lat, lng];
marker.setLatLng(newLatLng).update();
circle.setLatLng(newLatLng);
map.fitBounds(circle.getBounds());
}, 200);