1

I want to dynamically populate a marker popup via a JavaScript object.

I have a JavaScript object like so:

{address: "92101 S Martin Ave.", address2: "", agent_name: "mr smith", 
animal: "sheep", car: "honda", city: "Chicago", county: "Cook County", ID: "1", 
latitude: "41.718986", longitude: "-87.550646", postalcode: "60617", 
stateProvince: "IL", status: "GS"}

I want to be able to loop thru all of properties within the object and display those within the popup.

I have tried the below:

for (var j = 0; j < Object.keys(data).length; j++) {
                var marker = L.marker([data[j].latitude, data[j].longitude]).addTo(markers);
                marker.bindPopup(data[j]);

This does not work.

4
var yourData = getInfoFrom(yourObject).join(" <br>");

L.marker([63.43, 10.395]).addTo(map)
.bindPopup(yourData)
.openPopup();

function getInfoFrom(object) {
  var popupFood = [];
  for (var key in object) {
    if (object.hasOwnProperty(key)) {
      var stringLine = "The " + key + " is " + object[key];
      popupFood.push(stringLine);
    }
  }
  return popupFood;
}

Example popup with info from object properties

var yourObject = {
  address: "92101 S Martin Ave.",
  address2: "",
  agent_name: "mr smith",
  animal: "sheep",
  car: "honda",
  city: "Chicago",
  county: "Cook County",
  ID: "1",
  latitude: "41.718986",
  longitude: "-87.550646",
  postalcode: "60617",
  stateProvince: "IL",
  status: "GS"
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.