Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update markers in gmaps without refreshing the map?

Tags:

javascript

I'm ussing gmaps.js to display a basic google map with a marker placed on the current location. I am storing latitude and longitude coordinates in variables and using them to define the longitude and latitude. The Latitude and Longitude variables are updated from my server constantly. When this happens, the map displays the marker in a new position on the map however the entire map refreshes. I would like simply to just update the marker and keep the map from refreshing. Is there a way to do this?

<script> 
var map;
var Latitude = //this is being updated from my server constantly
var Longitude = //this is being updated from my server constantly
$(document).ready(function(){
  map = new GMaps({
    el: '#map',
    lat: Latitude,
    lng: Longitude
  });
  map.addMarker({
    lat: Latitude,
    lng: Longitude,
    title: 'Lima',
    details: {
      database_id: 42,
      author: 'HPNeo'
    },
    click: function(e){
      if(console.log)
        console.log(e);
      alert('You clicked in this marker');
    },
    mouseover: function(e){
      if(console.log)
        console.log(e);
    }
  });
  map.addMarker({
    lat: -12.042,
    lng: -77.028333,
    title: 'Marker with InfoWindow',
    infoWindow: {
      content: '<p>HTML Content</p>'
    }
  });
});
</script>
like image 218
Brandon Avatar asked Nov 24 '25 06:11

Brandon


1 Answers

// 1. Create a marker and keep a reference to it:

var latLng = new google.maps.LatLng(-12.042, -77.028333),
    marker = new google.maps.Marker({ position: latLng , map: map });

marker.setMap(map);

// 2. Move it around by setting a new position:

var newPosition = new google.maps.LatLng(-12.042, -78.028333);
marker.setPosition(newPosition);
like image 176
Johan Avatar answered Nov 25 '25 20:11

Johan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!