Brandon
Brandon

Reputation: 151

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

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>

Upvotes: 3

Views: 2499

Answers (1)

Johan
Johan

Reputation: 35213

// 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);

Upvotes: 1

Related Questions