0
votes

I'm using Mapquest API and Leaflet to display a map with markers on a web page. Leaflet reference: https://leafletjs.com/examples/quick-start/

The button should add a marker at the specified coordinate when the button is clicked. For some reason, it doesn't seem to be working. Here is my script:

var L; 
window.onload = function() { //loads map, center etc.
        L.mapquest.key = 'O5L5sKXrVY1AYIpiS2xVMvsLgAxUSw32';
        var map = L.mapquest.map('map', { 
          center: [37.641313, -122.290785],
          layers: L.mapquest.tileLayer('map'),
          zoom: 10
        });

//add markers and other map shapes here.

//trying to get it to add based on input.
    document.getElementById('mrkbtn').onclick = function addMarker() {
    L.marker(document.getElementById('inputText').value).addTo(map); }

    }

and here is the HTML button:

<div class="centerBtn">
<input id="inputText" placeholder="insert coordinates"></input>
<button id="mrkbtn" onclick="addMarker()">Add Marker to Map</button>
</div>

<br>
<div id="map"></div>

The button will add a marker when there are coordinates inside of L.marker() as follows:

L.marker([37.641313, -122.290785]).addTo(map);

however, when I changed what is inside L.marker() to try to grab the input value, it does not work. This is the part of the script where I'm making a mistake:

L.marker(document.getElementById('inputText').value).addTo(map);

I'm new to this, thanks so much for any assistance.

1

1 Answers

0
votes

L.marker(...).addTo(map) needs an array of numbers. You are using the constructor in a wrong way.

Let's pretend that the coordinates in your input are separated by a comma like:

13.443521,42.112345

Your function should be something like that:

document.getElementById('mrkbtn').onclick = function addMarker() {    
    L.marker((document.getElementById('inputText').value).split(',')).addTo(map); }
}

This should work because the split function is returning an array.