Drag and Drop Geocode Addresses Leaflet.js

29 Jul

I was playing with HTML 5 Drag and Drop and decided to try to make a map where I could drag a list of addresses on to a Leaflet map and have it display them as markers. I have used OpenStreetMap for Geocoding, but in this example I needed to use my ArcServer Geocode service. This was implemented via the ESRI REST API.

<html>

<head>
<title>Leaflet Drag and Drop Geocode from ArcServer Geocode Service</title>
<link rel=”stylesheet” href=”http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css&#8221; />
<style>
#map{
height: 100%;
width:100%;
}
</style>
</head>
<body>
<script src=”http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js”></script&gt;
<div id=”map” ></div>
<script>
var map = L.map(‘map’,
{
center: [35.10418, -106.62987],
zoom: 9
});
L.tileLayer(‘http://{s}.tile.osm.org/{z}/{x}/{y}.png’).addTo(map);

function handleGeocode(evt) {
evt.stopPropagation();
evt.preventDefault();

var files = evt.dataTransfer.files; // FileList object.
var reader = new FileReader();
reader.onload = function(event) {

var temp=event.target.result;
var text=temp.replace( /\n/g, “,” );
var c=text.split(“,”);

for(i=0;i<c.length;i++){
url1=”http://ArcServer Name/ArcGIS/rest/services/AddressLocator/GeocodeServer/findAddressCandidates?Street=”;
url2=String(c[i]);
url3=”&outFields=&outSR=4326&f=pjson”;
url=url1.concat(url2,url3);
var xhReq = new XMLHttpRequest();
xhReq.open(“GET”, url, false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
var d=JSON.parse(serverResponse);

if(typeof d.candidates[0] == ‘undefined’){alert(“error in address: “+url2);}
else{
L.marker([parseFloat(d.candidates[0].location.y),parseFloat(d.candidates[0].location.x)]).addTo(map).bindPopup(url2);
}

}

}
var s = reader.readAsText(files[0],”UTF-8”);

}

function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = ‘copy’; // Explicitly show this is a copy.
}

// Setup the dnd listeners.
var dropZone = document.getElementById(‘map’);
dropZone.addEventListener(‘dragover’, handleDragOver, false);
dropZone.addEventListener(‘drop’, handleGeocode, false);

</script>
</body>
</html>

Leave a comment