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.

asked Nov 7, 2017 at 19:24

1 Answer 1

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"
};
answered Nov 7, 2017 at 21:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.