django-webmapper /webmapper/static/webmapper/core.js

Language Javascript Lines 416
MD5 Hash 474e082d338fbe75d36e9779bdd3524f
Repository https://bitbucket.org/svevang/django-webmapper.git View Raw File View Project SPDX
| Open JSFiddle
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/* webmapper.js */

window.webmapper = (function(webmapper){

  if(typeof window.console === "undefined"){
    (function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();)b[a]=b[a]||c;})(window.console=window.console||{})
  }

  webmapper.errorHandler = {error:function(){
      // TODO: an error reporting system, display messages to the User
    }
  }

  webmapper.ApiParams = {
    // construct and store url paramters on a per Model/Collection basis

    // helper function to build query param list 
    serializeQueryParams: function(pairList){
      var str = []
      _(pairList).each(function(pair){
        str.push(encodeURIComponent(pair[0]) + "=" + encodeURIComponent(pair[1]))
      })
      return str.join("&")
    },

    // models and collections can build up api call params
    // by setting and deleting specific key/value pairs
    setApiParam:function(param, value){
      if(!this._apiParams)
        this._apiParams = []
      this._apiParams.push([param, value])
    },

    url: function(apiParameters){
      var baseUrl = this.urlRoot + (this.id ? this.id + "/" : "")
      var params = []

      if(apiParameters){
        // if we are passed any api parameters, use those
        params = apiParameters
      }
      else{
        // otherwise if we have set any parameters on this model/collection
        // accumulate those and append them to the url
        if(this._apiParams)
          _(this._apiParams).each(function(pair){params.push(pair)})
        if(this.collection && this.collection._apiParams)
          _(this.collection._apiParams).each(function(pair){params.push(pair)})
      }

      if(params.length > 0)
        baseUrl = baseUrl + '?' + this.serializeQueryParams(params)

      return baseUrl
    },

  }

  webmapper.BaseModel = Backbone.Model.extend(_.extend(webmapper.ApiParams,{
    isNew: function(){
      return ( typeof this.id == 'undefined' || this.id == "new")
    }      
  }))
  webmapper.BaseCollection = Backbone.Collection.extend(webmapper.ApiParams)

  webmapper.Map = webmapper.BaseModel.extend({

    urlRoot: webmapperConstant['api_maps_url'],

    bindEvents:function(){
      var map = this

    },
    initialize: function(opts){

      this.loading = $.Deferred() 

      this.templateStore = $('<div></div>')

      var defaultOptions = {
        fillContainer : false,
        applicationViews : [],
        scrollZoom : false,
        tools : [
          new webmapper.tools.MarkerTool(),
          new webmapper.tools.KmlTool()
        ]
      }
      this.options = _.extend(defaultOptions, opts)

      if(this.options.domId)
        this.baseEl = $('#'+this.options.domId)
      else
        this.baseEl = this.options.baseEl || null

      this.tools = this.options.tools 
      this.applicationViews = this.options.applicationViews 

      // FIXME, need to override the construtor, pull args out and then 
      // pass the rest to initialize, or maybe whitelist model attributes
      this.unset('baseEl',{silent:true})
      this.unset('tools',{silent:true})
      this.unset('applicationViews',{silent:true})

      if(this.isNew() && this.id != "new" )
        this.mapLoadedPromise = this.save()
      else
        this.mapLoadedPromise = this.fetch()

      _.bindAll(this)

      this.bindTools()
      this.bindApplicationViews() 

      var map = this

      // bootstrap the application
      $.when(map.mapLoadedPromise).then(function(){

        map.mapPane = new webmapper.MapPane({id: map.get('map_pane_id') || 'new'})
        map.mapPane.map = map

        var mapViewArgs = {model:map}
        if(map.baseEl){
          mapViewArgs.el = map.baseEl
        }

        map.view = new webmapper.MapView(mapViewArgs)

        $.when(map.mapPane.fetch()).then(function(){

          if(map.baseEl){
            map.view.render()
            // create map widget views render and append to map DOM
            map.mapPane.initializeMapPaneView()
          }

          // create geo attrs
          map.kmlLayers = new webmapper.KmlLayerCollection([], {map:map})
          map.points = new webmapper.PointCollection([], {map:map})
          map.polygons = new webmapper.PolygonCollection([], {map:map})

          if(map.isNew()){
            map.loading.resolve()
            map.trigger('loaded')
            return
          }
          map.trigger('prepare-sync', map)

          $.when(map.kmlLayers.fetch(), 
                 map.points.fetch(), 
                 map.polygons.fetch())
            .then(function(){

              // tools and application views can bind to various events
              map.trigger('init-ready', map)
              map.trigger('attach-kml',  map.kmlLayers)
              map.trigger('attach-points',  map.points)
              map.trigger('attach-polygons', map.polygons)
              map.trigger('init-complete', map)

              map.loading.resolve()
              map.trigger('loaded')

            })
        })
      })
      return this
    },

    // Save the Map and MapPane
    create:function(){
      
      var created = $.Deferred() 
      var map = this

      if(this.isNew()){
        this.save().done(function(){
            map.mapPane.id = map.get('map_pane_id')
            map.mapPane.fetch().done(function(){
              created.resolve()

          }).fail(function(){
            created.reject("MapPane fetch failed")
          })
        }).fail(function(){
          created.reject('Map create failed') 
        })  
        return created
      }
      else{
        throw('cannot create an existing map') 
      } 

    },

    bindTools:function(){

      var map = this

      _(this.tools).each(function(tool){
        tool.bindMap(map)
      })

    },

    bindApplicationViews:function(){

      var map = this

      _(this.applicationViews).each(function(view){
        view.bindMap(map)
      })

    },

    getTemplate:function(templateDomId){
      return webmapperConstant.templates[templateDomId]
    },

    getCurrentPane: function(){
      return this.mapPane
    },

  })

  webmapper.MapView = Backbone.View.extend({

    tagName: 'div',
    className: 'webmapper-map',

    render: function(){

      // build the map dom
      this.$el.css('position','relative')

      return this
    }

  })

  // MapPanes
  // --------

  webmapper.MapPane = webmapper.BaseModel.extend({

    initializeMapPaneView: function(args){

      // Initialize attributes specific to the map.
      var opts = args || {}
      opts.model = this

      // Create the map widget view.
      if(this.get('map_type') == "google")
        this.view = new webmapper.google.MapPaneView(opts)
      else if(this.get('map_type') == "openlayers")
        this.view = new webmapper.openlayers.MapPaneView(opts)
      else
        throw('unknown map type ' + this.get('map_type'))

      // Append the mapPane's rendered el to map DOM fragment.
      $(this.map.view.el).prepend(this.view.render().el)

      // trigger reflow on the map widget
      this.view.reflowSize()

      this.map.on('attach-kml', this.view.attachKML, this)
      this.map.on('attach-points', this.view.attachPoints, this)
      this.map.on('attach-polygons', this.view.attachPolygons, this)

      this.trigger('map-pane-initialized')
    },

    changeMapWidget: function(new_map_type){
      var mapPane = this

      // Supress map_type change event until the various attributes settle.
      mapPane.set({map_type:new_map_type},{silent:true})

      // We can save and reuse el.
      var el = mapPane.view.el
      mapPane.view.removeMapWidget()

      mapPane.initializeMapPaneView({el:el})

      // Impress the server state upon the widget.
      mapPane.view.syncMapWidget()

      // Re-setup tool delegations.
      mapPane.map.bindTools()
      mapPane.map.bindApplicationViews()

      // Our new widget is lacking the canonical layer: reattach the geo-models.
      this.map.trigger('attach-kml', this.map.kmlLayers)
      this.map.trigger('attach-points', this.map.points)
      this.map.trigger('attach-polygons', this.map.polygons)

      // Alert listeners that the map_type has changed.
      mapPane.trigger('change:map_type')

    },

    urlRoot: webmapperConstant['api_map_panes_url'],
    url:function(){
      return this.urlRoot + (this.id ? this.id + "/" : "")
    }

  })

  // MapPane Views 
  // -------------

  webmapper.AbstractMapPaneView = Backbone.View.extend({
    // provides custom events:
    //   * tiles-loaded

    // This class defines the interface to the concrete Google/Openlayers 
    // implementations. Webmapper map-types implement this interface.

    tagName: "div",
    className: "webmapper-mappane",

    initialize: function(opts){

      // if we are in an editing state,
      // set up the appropriate css class
      if(this.model.map.editing)
        $(this.el).addClass('editing')

    },

    // build up the attributes that handle events
    // pass in `translateFunc` to convert the event to an intermediate 
    // "webmapper" representation
    _eventAttrConstructor:function(eventName, translateFunc){
      var mapPaneView = this
      return function(){
        var eventArgs = arguments
        mapPaneView.trigger(eventName, translateFunc.apply(mapPaneView, eventArgs))
      }
    },

    render: function(){

      // calls to this should be idempotent across implementations
      this.removeMapWidget()

      var opts = this.model.toJSON()

      this.renderMapWidget()
      this.bindMapWidgetEvents()
      return this

    },

    reflowSize: function(){

      // allow the map to "reflow" in the container div
      if(this.model.map.options.fillContainer){
        this.$el.width(this.$el.parent().width())
        this.$el.height(this.$el.parent().height())
      }
      else{
        this.$el.width(this.model.get('width'))
        this.$el.height(this.model.get('height'))
      }

      this.trigger('reflow')

    },

    remove: function(){
      this.removeMapWidget()
      return Backbone.View.prototype.remove.call(this)
    },
    // Map Panes must implement a bare minimum interface
    paneDiv: function(){
      throw('not implemented')
    },
    renderMapWidget:function(){
      throw('not implemented')
    },
    bindMapWidgetEvents:function(){
      throw('not implemented')
    },
    syncMapWidget:function(){
      throw('not implemented')
    },
    removeMapWidget:function(){
      throw('not implemented')
    },
    getBounds:function(){
      throw('not implemented')
    },
    attachPoints:function(){
      throw('not implemented')
    },
    attachKML:function(){
      throw('not implemented')
    },
    attachPolygons:function(){
      throw('not implemented')
    },

    // Internal APIs must provide a mechanism to propagate widget attrs back
    // to the MapPane model. Something like:
    //   * propagateCenter
    //   * propagateZoom
    //   * propagateMapTypeId

    })

  return webmapper

})(window.webmapper || {});
Back to Top