Using MapView in different windows
I'm working on an app that has a need for a MapView to be used in multiple windows throughout. It works fine on the iPhone, but on Android there is a stack trace error about only having one MapView per application.
Ok, so only one MapView. I should be able to create the MapView in the app.js file and pass it around (clearing/creating annotations as I go), but when I do that the MapView loads a single time, but no where else.
Has anyone created anything on Android using MapViews in multiple locations? If so, how?
2 Answers
-
I have found this solution:
myMap.View = (function() { var singletonMap = null; var api = {}; api.removeAllAnnotations = function() { while (singletonMap.annotations.length) { singletonMap.removeAnnotation(singletonMap.annotations[0]); singletonMap.annotations.shift(); } }; api.addAnnotation = function(a) { if (singletonMap != null) { singletonMap.addAnnotation(a); singletonMap.annotations.push(a); } }; api.createMap = function(_args) { /* not existsa => create it */ if(singletonMap == null) { singletonMap = Titanium.Map.createView(_args); singletonMap.annotations = []; } else { this.removeAllAnnotations(); //may be other implementation for(var key in _args) { if(_args.hasOwnProperty(key)) { singletonMap[key] = _args[key]; } } } return singletonMap; } return api; })(); /* to call it: myMap.View.createMap(_args); */
-
For everyone that is struggling with this, essentially you will need to create a global instance of the mapview in Android, and then use that single instance throughout your application. This means:
- Adding and removing the mapview from the window/view so at there is at most one window/view using the mapview at a time
- Keeping a single javascript execution context throughout your application (otherwise map tiles will not refresh, and other weird bugs will happen from jumping execution contexts)
I have to say that, even then, Android mapview experience is not the best in my experience. Sometimes when I open my app, all the mapview tiles show up, and other times (without doing any changes at all), the tiles for outside starting area do not show up.