-1

I have a <script type="text/javascript"> included in my web page. This script is defining Markers for my Google Map among other things. There is another script included in this page which is referenced from another .js file. I need to, in the second script written in the separate JS file, change icons of markers dynamically, based on some condition.

Actually in the first page, I read data from a database table using PHP. Then use this data to write PHP statements like

echo '<script>';
echo 'function initMap() {';
//.... code code
echo 'var marker'. $recordIdFromDb .' = new google.maps.Marker({position:{lat: '.$recordData["lat"].', lng: '.$recordData["lng"].'}, map:map, icon: greenIcon});';

Let's say the last statement in the above PHP code prints into the web page:

var markerXYZ123 = new google.maps.Marker({position:{lat:123, lng:456}, map:map, icon: greenIcon})

Now, in the second script, I am doing some processing, as a result of which I first update some fields in the records of the database table which was the source of the data in the above mentioned first script.

Then, in the second script, I pull data from the same data table. Then, on the basis of some condition, I have to change the icon of the marker. For that I will have to use a statement like

markerXYZ123.setIcon(blah blah);

Now as noted above, XYZ123 suffix of the marker's name is actually the id of this record from the database. In the second script, I have this id. I need to dynamically form the name of the marker variable. Something like

("marker" + "XYZ123").setIcon(blah blah);

How do I do that? How do I dynamically form this variable name, in Javascript?

JBel
  • 329
  • 1
  • 5
  • 19

1 Answers1

2

Use an object indexed by id instead of a dynamic variable name. For example, in your first script:

const markers = {};
markers[<?= $recordIdFromDb; ?>] = new google.maps.Marker({
  position: {
    lat: <?= $recordData["lat"] ?>,
    lng: <?= $recordData["lng"] ?>,
  },
  map,
  icon: greenIcon,
});

Then in your other script, just use the recordIdFromDb that you have again to access the appropriate key in the markers object:

markers["XYZ123"].setIcon(...
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Hi, I get an error in the second `.js` file when I try to access the markers object: **Uncaught ReferenceError: markers is not defined** – JBel Aug 03 '18 at 07:04
  • 1
    Make sure to define `markers` in the *global scope* so that you can access it from your other script, otherwise you'll get a `ReferenceError` – CertainPerformance Aug 03 '18 at 07:06