sleort
sleort

Reputation: 193

How to store and change coordinates individually - Google Maps API

I am trying to make a program, where I can create some markers and then save their coordinates in an HTML-list. My problem is that the HTML-list and the markers are not linked to each other, so the displayed coordinates doesn't change when the marker is dragged to another place on the map.

This is the "marker-script" for Google Maps API

I know this will not work, since it isn't checking for the id. As you can see it creates an id(number) for the marker, which could be used to "link" it to the HTML list, with the same number/id. When a marker is dragged, the corresponding list-item should show the new coordinates. I just haven't figured out how I should do so.

var currentId = 0;
var uniqueId = function() {
    return ++currentId;
};
var markers = {};
function placeMarker(location) {
    var id = uniqueId();
    var elements = document.getElementsByTagName("li");
    var marker = new google.maps.Marker({
        id : id,
        position : location,
        map : map,
        draggable : true,
        animation : google.maps.Animation.DROP
    });
    document.getElementById('checkpoint-textbox').value = id;
    document.getElementById('checkpoint-textbox').setAttribute("dataid", id--);
    document.getElementById('checkpoint-textbox').value = id;
    google.maps.event.addListener(marker, "dragend", function(event) {

        //I need the code here I think, to specify which list is modified by the dragged marker.

        document.getElementById("coords").innerHTML = 'Coordinates: '
            + event.latLng.lat() + ', ' + event.latLng.lng();

        }
    });
}

Here is the list.

It is created with another script, but thats not important, since the problem is how it changes existing coordinates.

<ol>
    <li id="coords" dataid="0">Coordinates: 20.000, 20.000</li>
    <li id="coords" dataid="1">Coordinates: 30.000, 30.000</li>
</ol>

At the moment, it obviously only changes the upper one.

Upvotes: 0

Views: 607

Answers (1)

Dr.Molle
Dr.Molle

Reputation: 117314

ID's must be unique, you use the same ID for each <li/>. Depending on the browser always the first or last <li/> will be selected.

Give the elements unique id's or select them by their dataid-attribute

google.maps.event.addListener(marker, "dragend", function(event) {

  document.querySelector('ol li[dataid="'+this.get('id')+'"]').innerHTML = 
    'Coordinates: ' + event.latLng.lat() + ', ' + event.latLng.lng();

});

Upvotes: 2

Related Questions