Issue
I am using JavaScript library Leaflet in my Android app's WebView to display a map with markers. The markers represent location objects in my Android app so the position of the location and its id are sent to JavaScript by calling a function in JavaScript.
view.loadUrl("javascript:createLocationMarker(" + lat + "," + lon + "," + locationId + ");");
I don't know if this is really necessary to know because I guess the problem seems to be in JavaScript:
function createLocationMarker(lat, lon, locationId) {
var marker = L.marker([lat, lon]).addTo(map).on('click', function(locationId) {
Android.getLocationDetails(locationId);
});
}
The marker is created there where it should be created. Works fine!
The problem is the onClick callback function which is binded to the marker. When the user clicks on the marker a JavaScriptInterface in Android is called. That works fine BUT instead of the locationId which was transmitted as the marker was created the parameter of Android.getLocationDetails() is ALWAYS 0. So I guess JavaScript does not persist the locationId. I guess that because I debugged the line in my Android code which calls the function createLocationMarker() where the locationId is definetely right setted. Additionally when I hard code the locationId in my JavaScript code like Android.getLocationDetails(2); the locationId 2 is sent right to the JavascriptInterface in Android. So it must be a problem with JavaScript.
I hope there are a few JavaScript cracks who can help a noob like me to solve the problem.
Solution
You are overriding the variable (creating another local variable with the same name):
function createLocationMarker(lat, lon, locationId) {
var marker = L.marker([lat, lon]).addTo(map).on('click', function(locationId) {
Android.getLocationDetails(locationId);
});
}
Use a different name in order to access the locationId on the outer scope.
Answered By - Derek 朕會功夫
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.