Getting map data from Mapbox and displaying it on an HTML page

I have been working with Mapbox GL JS and successfully retrieved data in the console. However, I am facing issues when trying to display this data on an HTML page. Can anyone assist me with this problem? I specifically need the data inside mapdata to be shown on the HTML page. Additionally, I want the showStory condition to become true when clicking on a marker. I attempted to use ngFor with mapData but it did not work. The data from the console also does not appear when logging outside of Mapbox.

HTML:

   <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12" (click)="openFav()" *ngIf="showStory">
        <ul class="addressClass">
          <li><i class="fa fa-star-o" aria-hidden="true"></i></li>
          <li><b>Place/Name</b></li>
          <li>Country, City</li>
          <li>Postal Code, Address</li>
        </ul>
      </div> 

Ts:

public showStory:boolean = false;
this.ApiService
              .getAllPins()
              .subscribe(
                pins => {
                  this.places = pins.data;
                  this.points = this.places.map(function(pins) {
                    return {"name":pins.name,"lat":pins.lat,"lang":pins.lang,"address":pins.address,"category_name":pins.category_name,
                    "description":pins.description,"email":pins.email,"phone_number":pins.phone_number,"pin_media":pins.pin_media,
                    "country":pins.user_details.country,"user_name":pins.user_details.user_name};
                });
                  mapboxgl.accessToken = 'pk.eyJ1IjoicmFrc2hpdGhhMTkiLCJhIjoiY2pjcHl1YW5wMjR5czJ6bzdqdjZrbDRzeSJ9.OOqu6zVyNsXavzCsYoBdPA';
                    var coOrdinates = this.points;
                    var map = new mapboxgl.Map({
                      container: 'maps',
                      style: 'mapbox://styles/mapbox/streets-v9',
                      center: [coOrdinates[1].lat,coOrdinates[1].lang],
                      zoom: 3
                    });
                    map.on('load', function () {
                      for(var i=0; i< coOrdinates.length; i++) {
                        map.addLayer({
                        "id": "points" + i,
                        "type": "circle",
                        "paint":{
                          "circle-radius":15,
                          "circle-color":'#' + (Math.random().toString(16) + "000000").substring(2,8)    
                        },
                        "source": {
                          "type": "geojson",
                          "data": {
                            "type": "FeatureCollection",
                            "features":  [{
                                "type": "Feature",
                                "properties": {"field":coOrdinates[i],"name":coOrdinates[i].name},
                                "geometry": {
                                  "type": "Point",
                                  "coordinates": [coOrdinates[i].lat,coOrdinates[i].lang]
                                }
                              }]
                          }
                        }
                      });
                      var popup = new mapboxgl.Popup({
                          closeButton: false,
                          closeOnClick: false
                      });
                      map.on("mouseenter", "points" + i, e => {
                        this.id = e.features[0].layer.id;
                        map.setPaintProperty(e.features[0].layer.id, 'circle-radius', 20);
                        var coordinates = e.features[0].geometry.coordinates.slice();
                        var description = e.features[0].properties.name;
                        while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
                          coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
                       }
                       popup.setLngLat(coordinates)
                            .setHTML(description)
                            .addTo(map);
                      });
                      map.on("mouseleave", "points" + i, e => {
                        if(this.id) {
                          map.setPaintProperty(this.id, 'circle-radius', 15);
                          this.id = undefined;
                        } 
                         popup.remove();
                      });
                      map.on("click", "points" + i, e => {
                        this.id = undefined;
                        this.mapData = e.features[0].properties
                        for(var i=0; i< coOrdinates.length; i++) {
                          map.setPaintProperty('points'+i, 'circle-radius', 15); 
                        }
                        map.setPaintProperty(e.features[0].layer.id, 'circle-radius', 20);
                        this.showStory = true; 
                       this.mapData = JSON.parse(this.mapData.field);
                       console.log(this.mapData);
                      });
                      }
                    });
          }, error => {});

Answer №1

To display data from a component in HTML, you can utilize the innerHTML property.

Within the HTML section:

<li><b [innerHTML]="place"></b></li> 
<li [innerHTML]="Country, City"></li> 
<li [innerHTML]="Postal Code, Address"></li> 

And in the Ts section:

Include, this.place = this.mapData.place;

map.on("click", "points" + i, e => {
    this.id = undefined;
    this.mapData = e.features[0].properties;
    for(var i=0; i< coOrdinates.length; i++) {
        map.setPaintProperty('points'+i, 'circle-radius', 15); 
    }
    map.setPaintProperty(e.features[0].layer.id, 'circle-radius', 20);
    this.showStory = true; 
    this.mapData = JSON.parse(this.mapData.field);
    this.place = this.mapData.place; 
    console.log(this.mapData);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Ajax call is failing to trigger the success function

Can anyone assist me? My success function isn't working properly. The beforesend is functioning correctly and I've verified the variable s. It has a true value before the ajax call, so all validations are correct. Please take a look... function ...

Ways to initialize Nested Arrays in Angular applications

I have been experimenting with some code on Codepen. I am trying to load JSON data from a service and then use ng-repeat to display the arrays. The issue I'm facing is that while the first array loads successfully, the nested array "data.cities" is n ...

Show the entire phrase within a Bootstrap modal with the help of jQuery, instead of just the initial

I have a PHP script that fetches a name from a database, and I'm using jQuery to display that name as HTML inside a Bootstrap modal when a button is clicked. However, the issue I'm facing is that when the name contains spaces, only the first word ...

Protractor's isDisplayed method may return a false value for an element that is actually visible

UPDATE #4: Eureka!! I made a breakthrough by recursively navigating through the parent nodes and returning the same values as shown below. Surprisingly, one of the parent nodes - the inner mat-drawer-container - also returned false for isDisplayed, while ...

Prevent the need to keep deleting text when entering data into selectize.js <select>_dropdown

I am working with a single choice <select> element that has been enhanced using selectize.js. This <select> element already has an option pre-selected as the current value. To change this value, users must: Click on the drop-down control, Pr ...

Transforming JSON in Node.js based on JSON key

I am having trouble transforming the JSON result below into a filtered format. const result = [ { id: 'e7a51e2a-384c-41ea-960c-bcd00c797629', type: 'Interstitial (320x480)', country: 'ABC', enabled: true, ...

adding a JavaScript module to a handlebars template

I have a few different files that I'm working with: In the server.js file, I have the following code: app.get('/main/:id', function(req, res) { res.render('main', { products: products }); }) Within the main.hbs file, I have ...

How can you disable a single button when clicked using the map method, and update the className after a timer runs out in React?

Is there a way to disable only one button when clicked using the map method? I currently have a disabled hook that affects all pressed buttons. Also, how can I revert the 'current__events__hot-price disabled' className back to 'current__even ...

Encountering a glitch while attempting to render with the select tag in React.js

I have developed two functions that generate JSX content and created a logic to display each function based on the user's choice: const Register = () =>{ const [value, setMyValue] = useState() function Zeff(){ return( <div> <h1& ...

Why isn't the connect.use() function working in Node.js?

I have been studying and applying examples from a book to learn Node.js. While replicating one of the examples, which involved creating a middleware, I encountered an error when trying to run the JavaScript file. The error message stated "undefined is not ...

Equalize the color of overlapping background events with non-overlapping background events in fullcalendar

events:[ {overlap:false, display:'background', start:'2021-12-23 10:15:00', end:'2021-12-23 10:30:00'}, {overlap:false, display:'background', start:'2021-12-23 10:30:00', end:'2021-12-23 10:45:00&a ...

Swapping out a class or method throughout an entire TypeScript project

Currently, I am working on a software project built with TypeScript. This project relies on several third-party libraries that are imported through the package.json file. One such library includes a utility class, utilized by other classes within the same ...

html inserting line break using label

I am attempting to dynamically set text to a label using jQuery. However, I am having trouble getting the <br> or \n to create new lines. Instead, all the text displays on the same line and wraps around. If you want to see my code in action, ch ...

Steps for assigning an id to an element using Selenium

When using Selenium, you have the ability to access the underlying DOM of the browser being manipulated through IWebElement instances. For example: IWebElement domWrapper = driver.FindElement(By.Name("q")); But what if you have the "domWrapper" instance ...

Guide on how to use Vue's watch feature to monitor a particular property within an array

I am interested in observing the "clientFilter" within an array TableProduit: [ { nr_commande: 0, date_creation: "", id_delegue: "1", clientFilter: "" } ], ...

Display the output returned from the AJAX request (HTML and/or JavaScript)

How can I effectively render content from an ajax call when the response may include html and/or javascript? I used to rely on document.write() for synchronous calls, but now that I need to use asynchronous calls, I have to find a different approach to dis ...

Guide for implementing smooth fade in and out effect for toggling text with button click

I have this code snippet that toggles text on button click: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> function toggleText(){ ...

Vue JS - Troubleshooting Checkbox Validation Error During Form Submission

When a user fills out my registration form, there is a checkbox to confirm acceptance of the terms and conditions. Currently, the validation error for this checkbox appears immediately upon hitting submit, even though the checkbox starts as unchecked. The ...

Click Function for Modifying the Content of a Popup Window

I'm a beginner in JavaScript and I need help figuring out how to achieve the following task. Essentially, my goal is to have lines of code like this: <a onclick="JavascriptFunction(0000000)"><img src="image1.png"></a> The number w ...

Learn the process of filtering an array using another array

I have a collection of items set up in the following format. items = [ { id: 1, status : "Active" // Other fields tags : [{val: 'IGM', color: 'light-success' }, {val: 'Gated Out', colo ...