0

I am creating an app with leaflet that shows a route on a map based on the button clicked. For example when you click on "button1", the associated route is successfully displayed on the map (i.e. map.addLayer(route1Data); works). When you click on either button2 or button3, the route for button1 should be removed. For some reason map.removeLayer(route1Data) is not working.

I am testing button1 at this time.

Why is the layer not being removed?

Steps, 1. whichRoute() --> 2. Tracks() --> vlocation()

See scripts below:

HTML

<html>
<head>
<title>Route Chooser</title>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/black-tie/jquery-ui.css" type="text/css" /> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js" charset="utf-8"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js" charset="utf-8"></script>
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
    <script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
    <script type="text/javascript" src="../js/chooseRoute.js"></script>

    <script type="text/javascript">
    var vdata;
    $(document).ready(function() 
    {
        whichRoute();
    }); //end of ready

</script>
</head>
<body>
<div id='bttnSelect'>
    <button class='rtbttn' id='rt1' name='rt1' data-name="route_1">Route 1</button>
    <button class='rtbttn' id='rt2' name='rt2' data-name="route_2">Route 2</button>
    <button class='rtbttn' id='rt3' name='rt3' data-name="route_3">Route 3</button>
</div>

<div id="map_canvas" style="width: 1400px; height: 600px"></div>

<script>

    var map = new L.Map('map_canvas',{doubleClickZoom:false,zoomControl:false}).setView(new L.LatLng(11.2269,  -60.60760), 12);
    mapLink = '<a href="http://openstreetmap.org">OpenStreetMap</a>';
    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: 'Map data &copy; ' + mapLink,
        maxZoom: 18,
        }).addTo(map);

        var osmURL = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; 
        var mapLink = '<a href="http://openstreetmap.org">OpenStreetMap</a>';
        var osmLayer = L.tileLayer(osmURL, {attribution: 'Map data &copy; ' + mapLink});

    var currentRoute;
    function vlocation(locx, xx){

        var vdatax = locx;
        console.log('value current route before: ',currentRoute);
        if (currentRoute) map.removeLayer(currentRoute);
        var currentRoute = L.polyline(vdatax);
        console.log('value current route after: ', currentRoute);
        map.addLayer(currentRoute);//For show

} //end vloc

</script>

</body>
</html>

Javascript

function tracks(xx){
$.ajax({
    url:"../php/vTrackerv2.php", 
    type: "POST",
    dataType: 'json',
    //cache: false,
    success:function(rdata)
    {
        var locData = [];
        for (x=0; x< rdata.length-27; x++) {
            var loc = [];
            loc.push(parseFloat(rdata[x].latitude)); 
            loc.push(parseFloat(rdata[x].longitude));
            locData.push(loc);
        }
    vlocation(locData,xx);
    }, //end success
  });
};


function whichRoute(){
$('#bttnSelect').on('click', function(event) {
    // Retrieve the 'name' data attribute of the <a/> tag that the user clicked.
    var bttnClicked = $(event.target).closest('button').data('name');
    if (bttnClicked == 'route_1'){
        console.log("You clicked on:", bttnClicked);
        tracks(1);
    }

    if (bttnClicked == 'route_2'){
        tracks(2);
        console.log("You clicked on:", bttnClicked);
    }

    if (bttnClicked == 'route_3'){
        tracks(3);
        console.log("You clicked on:", bttnClicked);
    }

  });
}
  • 1
    Can you make a fiddle or [plunker](plnkr.co please? – pk. Apr 13 '15 at 13:16
  • @pk. I created a fiddle (jsfiddle.net/joepub/60zcbhcf/3) But having a cross domain issue. I enable CORS but still no luck. Any suggestions would be appricated, – ChrisJ Apr 15 '15 at 16:38
  • jsfiddle will only let you make cross domain calls with https. I updated the fiddle with the https leaflet files and copied your chooseRoute code into the javascript window. But when I click on the buttons I get errors because of the cross domain php file. Are you able to force your server to use https to serve the php file? – pk. Apr 15 '15 at 18:43
  • @ok I've configured the sever to use https. I made the change to your fiddle and got the following error: net::ERR_INSECURE_RESPONSE – ChrisJ Apr 15 '15 at 23:43
  • In firefox (but not chrome), the following works as the url cloudtobago.com/vTracker/php/vTrackerv2.php?route=1 but not in jsfiddle – ChrisJ Apr 16 '15 at 0:35
2

The route1Data you are trying to remove is not the original route data that was added.

You need to declare your layer outside of vlocation.

I modified vlocation to the follow and it adds and removes the layer in my fiddle.

var currentRoute;
function vlocation(locx, xx) {
    var vdatax = locx;
    if (currentRoute) map.removeLayer(currentRoute);

    if (xx == 1) {
        currentRoute = L.polyline(vdatax);
        map.addLayer(currentRoute);
    }
    if (xx == 2) {
        currentRoute = L.polyline(vdatax);

    }
    if (xx == 3) {
        currentRoute = L.polyline(vdatax);

    }
} //end vloc

Here's a link to the fiddle too.

  • I see and understand what you did. But for some reason I can't get it to work... currentRoute is not holding the value when I click on another button. I've updated my vlocation function to reflect what I have now – ChrisJ Apr 16 '15 at 18:29
  • When I click on a button, the value of currentRoute is always 'undefined' even of there was a previous button clicked – ChrisJ Apr 16 '15 at 18:45
  • pk... It seems like I mistakenly gave your answer a down vote without realizing I did. I'm sorry. Is there a way I can change it to an up vote?? – ChrisJ Apr 16 '15 at 19:04
  • I'm not sure how to change to up vote. Were you able to get things working? – pk. Apr 16 '15 at 19:26
  • I found this post meta.stackexchange.com/questions/5212/… In the Limits on Changing Votes section it says this "Exception two: you may change your vote after every time the post is edited. A new window starts with the first vote you cast after each edit." – pk. Apr 16 '15 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.