import L from 'leaflet';
import { getJSON } from '@utils';

import { getData } from '../shared/data';
import { DEFAULT_POSITION } from '../shared/carto';

import {
  drawCadastre,
  drawQuartiersPrioritaires,
  drawUserSelection
} from './carto/draw';

function initialize() {
  if (document.getElementById('map')) {
    getJSON(getData('carto').getPositionUrl).then(
      position => initializeWithPosition(position),
      () => initializeWithPosition(DEFAULT_POSITION)
    );
  }
}

addEventListener('turbolinks:load', initialize);

function initializeWithPosition(position) {
  const map = L.map('map', {
    scrollWheelZoom: false
  }).setView([position.lat, position.lon], position.zoom);

  L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution:
      '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);

  const data = getData('carto');

  // draw external polygons
  drawCadastre(map, data);
  drawQuartiersPrioritaires(map, data);

  // draw user polygon
  drawUserSelection(map, data);
}

@@ -1,64 +1,4 @@
-import L from 'leaflet';%0Aimport %7B getJSON %7D from '@utils';%0A%0A
 impo
@@ -44,32 +44,23 @@
 mport %7B 
-DEFAULT_POSITION
+initMap
  %7D from 
@@ -78,17 +78,16 @@
 carto';%0A
-%0A
 import %7B
@@ -248,264 +248,50 @@
     
-getJSON(getData('carto').getPositionUrl).then(%0A      position =%3E initializeWithPosition(position),%0A      () =%3E initializeWithPosition(DEFAULT_POSITION)%0A    );%0A  %7D%0A%7D%0A%0AaddEventListener('turbolinks:load', initialize);%0A%0Afunction initializeWithPosition(
+const position = getData('carto').
 position
 ) %7B%0A
@@ -286,22 +286,22 @@
 position
-) %7B%0A
+;%0A 
   
+ 
 const ma
@@ -308,101 +308,24 @@
 p = 
-L.map('map', %7B%0A    scrollWheelZoom: false%0A  %7D).setView(%5Bposition.lat, position.lon%5D, 
+initMap(
 position
 .zoo
@@ -324,202 +324,13 @@
 tion
-.zoom
 );%0A
-%0A
   
-L.tileLayer('http://%7Bs%7D.tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png', %7B%0A    attribution:%0A      '&copy; %3Ca href=%22http://osm.org/copyright%22%3EOpenStreetMap%3C/a%3E contributors'%0A  %7D).addTo(map);%0A%0A
   co
@@ -355,24 +355,26 @@
 ('carto');%0A%0A
+  
   // draw ex
@@ -389,16 +389,18 @@
 olygons%0A
+  
   drawCa
@@ -418,16 +418,18 @@
  data);%0A
+  
   drawQu
@@ -463,16 +463,18 @@
 ta);%0A%0A  
+ 
+ 
 // draw 
@@ -486,16 +486,18 @@
 polygon%0A
+  
   drawUs
@@ -520,10 +520,64 @@
  data);%0A
-%7D
+  %7D%0A%7D%0A%0AaddEventListener('turbolinks:load', initialize);
 %0A

use initMap in new design carto