Search code examples
javascriptmapboxopenstreetmapgeojson

Unable to access GeoJSON properties with ":" using JS variable


I am currently following the tutorial on Mapbox to build a store locator with a map.

I'm having problems displaying data from my GeoJSON file that I got from Turbo Overpass. Example of the GeoJSON being used :

"properties": {
    "@id": "node/5750820619",
    "addr:city": "Caissargues",
    "addr:housenumber": "180",
    "addr:postcode": "30132",
    "addr:street": "Avenue de la Vistrenque",
    "description:covid19": "horaires légèrement réduits",
    "name": "Bio Marché",
},

In my Javascript file I can access properties such as name using this code :

var details = listing.appendChild(document.createElement('div'));
details.innerHTML = prop.addr:city;

...but am unable to figure out how to access the addr:city or addr:postcode field as I either get an unexpected identified in vs code or it returns a undefined value in the website. I've tried using prop.addr:city;, prop.addr/':city'/; and other ways proposed on websites.

If someone could point me in the right direction or propose the solution I would be very grateful. Thanks !


Solution

  • You should access these properties like this:

    details.innerHTML = prop['addr:city'];
    

    This works because in Javascript object properties can always be accessed using these brackets.

    For example this:

    const a = prop.a;
    

    is equal to

    const a = prop['a'];
    

    However using the last syntax Javascript is a lot more relaxed. You could even do this:

    const property = prop['some property with lots of spaces'];