Edwin Jovany Herrera
Edwin Jovany Herrera

Reputation: 13

Add multiple markers to rails map

I have implemented google maps on my ruby on rails web application. I am displaying the map just fine and I am also able to place markers just fine. My issue is that I have 2 JavaScript functions that refresh the map and drop a marker on the map. I want to be able to keep the current map and just add another marker to the map with my functions. How can stop my map from refreshing to show more than 1 marker?

// application.js

var map;

function initMap() {
  var lat=29.732585;
  var lng=-95.462830;

  map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 29.7604, lng: -95.3698},
      zoom: 10.25,
  });
  var marker = new google.maps.Marker({
      position: {lat:29.732585,lng:-95.462830},
      map: map
  });
}

function getEmployee() {
  map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 29.7604, lng: -95.3698},
      zoom: 10.25,
  });
  var marker = new google.maps.Marker({
      position: {lat:29.7154,lng:-95.3893},
      map: map
  });
}

function getLocation() {
  map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 29.7604, lng: -95.3698},
      zoom: 10.25,
  });
  var marker = new google.maps.Marker({
      position: {lat:29.7560,lng:-95.3573},
      map: map
  });
}

Upvotes: 0

Views: 666

Answers (1)

Ilya Konyukhov
Ilya Konyukhov

Reputation: 2791

When calling getEmployee() or getLocation() you recreate the map, by calling new google.maps.Map. That's why your map is refreshing on each call.

Just remove this map recreating from these 2 functions. You create a map on initMap() call and store it in a global variable map, so it can be used in getEmployee() and getLocation() where you create a marker.

Upvotes: 2

Related Questions