Add map marker after clicking icon

101 Views Asked by At

I am creating a page to do a basic search for breweries and am displaying information pulled from an API about breweries and would like to display the location on a map from the MapQuest API.

I know how to make a static marker, but is it possible to create a marker after a click event that uses the latitude and longitude from the JSON file? So after entering in a search term to populate the results, I want to be able to click a result and then have a marker added to the map. Is this even possible?

picture of my website project

Here is my code for the map:

var L;

window.onload = function() {
    L.mapquest.key = 'hidden';

    // 'map' refers to a <div> element with the ID map
var map = L.mapquest.map('map', {
    center: [38.584487, -90.266699],
    layers: L.mapquest.tileLayer('hybrid'),
    zoom: 11
});

map.addControl(L.mapquest.control({ 
    position: 'bottomright' 
}));

L.marker([38.584487, -90.266699], {
    icon: L.mapquest.icons.marker({
        primaryColor: '#22407F',
        secondaryColor: '#3B5998',
        shadow: true,
        size: 'sm',
        symbol: 'A'
    })
})

.bindPopup('Welcome to St. Louis! <br> Find more info <a href="https://www.stlouis-mo.gov/">  here! </a>')
.addTo(map);
}

-- and my code for displaying each brewery below the map:

// search bar using JS
const breweryList = document.getElementById('result');
const searchBar = document.getElementById('searchBar');
let brewerySpots = [];

searchBar.addEventListener('keyup', (e) => {
    const searchString = e.target.value.toLowerCase();


    const filteredBreweries = brewerySpots.filter(data => {
        return (
        data.name.toLowerCase().includes(searchString) || 
        data.city.toLowerCase().includes(searchString)
        );
    });
    displayBreweries(filteredBreweries);
});

const loadBreweries = async () => {
    try {
        const res = await fetch('https://raw.githubusercontent.com/openbrewerydb/openbrewerydb/master/breweries.json');
        brewerySpots = await res.json();
        displayBreweries(brewerySpots);
    } catch (err) {
        console.error(err);
    }
};

const displayBreweries = (breweries) => {
    const htmlString = breweries
        .map((brewery) => {
            return `
            <li class="brewery col">
                <h3><a href="${brewery.website_url}">${brewery.name}</a></h3>
                <address> Location: ${brewery.street}, 
                ${brewery.city}, ${brewery.state}</address>
                <p>Type: ${brewery.brewery_type}</p>
                <i style='font-size:24px' class='fas' >&#xf041;</i>
            </li>`
        })
        .join('');
    breweryList.innerHTML = htmlString;
};

loadBreweries();

It seems like all of the examples and tutorials I have found pertain to clicking on the map to add a marker, but I want to click a hyperlink on my page that will use the latitude and longitude from the JSON data to add a marker.

Here is my HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
  <script src="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.js"></script>
  <link type="text/css" rel="stylesheet" href="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.css"/>
  <link rel="stylesheet" href="../styles/style.css" />
  <title>Beer30!</title>

</head>
<body>
  <nav class="navbar">
    <a href="#" class="navbar__logo">
      <i class="fas fa-beer"></i>
    </a>
    <div class="navbar__bars">
      <i class="fas fa-bars"></i>
    </div>
    <div class="navbar__menu">
      <a href="./index.html" class="navbar__menu--links">Home</a>
      <a href="./breweries.html" class="navbar__menu--links">Breweries</a>
      <a href="#" class="navbar__menu--links">About</a>
      <a href="./signup.html" class="navbar__menu--links" id="button">Sign Up</a>
      <a href="#" class="navbar__menu--links" id="button">Log In</a>
    </div>
  </nav>

  <!-- map placeholder -->
  <div id="map"></div>

  <!-- search field-->
  <div class="container" style="width:900px">
    <h2 align="center" style="color: rgb(231, 231, 231)">Search for Breweries</h2> 
    <h4 align="center" style="color: rgb(231, 231, 231)">Use the search field below to filter by city or brewery name!</h4>
    <br>
    <div id="searchWrapper">
      <input type="text" name="searchBar" id="searchBar" placeholder="Search for a brewery" class="form-control">
    </div>
    <br>
    <ul class="list-group" id="result"></ul>
  </div>
  <br><br>

  <hr>
  <!-- area to hold list of breweries -->
  <select id="breweries-dropdown" name="breweries"></select>
  <br><br>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
  <script
  src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
  crossorigin="anonymous"></script>
  <script src="../app/script.js"></script>
</body>
</html>
1

There are 1 best solutions below

0
MQBrian On

NICE! I used the Untappd API to do something similar several years ago.

I think your link will need to have an index/reference back to the list of breweries so the code can grab the correct lat/lng from the link, place the marker on the map (the same way the initial St Louis marker is added) and recenter on it.