GreenInfo-Network / MobileMapStarter2

Get a mobile app together in short order using Cordova + Leaflet + Bootstrap
Apache License 2.0
3 stars 0 forks source link

Triggering map setView on button/link click #20

Closed TinArgus closed 6 years ago

TinArgus commented 6 years ago

This seems like it should be easy to do, but I'm struggling to get it to work. For an app that I am developing, I want a link (or button) on the welcome page to trigger a setView event on the map and switch to the map pane. Is there an easy way to do this? Thanks!

gregallensworth commented 6 years ago

To connect a button to the behavior of zooming the map, you'd first create a utility method like this:

// add to controller.js a method for setting calling setView() or setCenter()
// the zoom param is optional; if omitted will simply call setCenter()
zoomTheMap (lat, lng, zoom) {
    if (zoom !== undefined) {
        this.map.setView([ lat, lng ], zoom);
    }
    else {
        this.map.setCenter([ lat, lng ]);
    }
}

Then call it as usual from HTML, in conjunction with selectPage() to also switch to the map:

<button ng-click="app.selectPage('map'); app.zoomTheMap(34.5, -118.0, 6);" class="btn btn-primary btn-lg">Zoom To A Place</button>
TinArgus commented 6 years ago

Awesome! Thank you for the clear and concise explanation. I have learned so much by working with this code and implementing it in my project! I appreciate your help...thanks again for making this available for the open source community!

TinArgus commented 6 years ago

I just wanted to post an update in case it might help someone in the future. After successfully implementing this code, I wanted to also attach an 'addLayer' action to the button so that information relevant to the location was displayed. I tried to toss this command in at the end of the Zoom function, but it wasn't working. Finally, I figured out that the only way to call the layer group variable was to make it as a global variable outside of the map initialization function where most of my code is executed. Once the scope was set right and the variable was made global, it worked perfectly!

Since this project is aimed at people who are newer to programming and may also struggle with the concept of scope, I thought adding this might be useful.