k4r573n/leaflet-control-osm-geocoder

enhancement: drop marker at geocoded location

Opened this issue · 4 comments

I'm working on a project where users will want to compare their address against a polygon layer. Once they find their address, they'll want to zoom out and pan to look at the polygon boundaries. How hard would it be to drop a pin at the location returned by the geocoder?

it shouldn't be too difficult - modify the callback function. Nominatum returns a lon lat position which is accessable by

var center = [results[0].lat, results[0].lon];

to set a marker should work by

var marker = L.marker(center);
this._map.addLayer(marker);

but it doesn't - seams like my break in JS develloping was to long

Hm. I tried a couple variations on that and couldn't get it to work. I'll keep trying. Thanks for the idea!

Here's a solution I came up with. You could use a standard marker instead of the Leaflet Awesome Markers plugin shown in the example.

var searchBounds;
var  addressSearchResults;

// OSM Geocoder
osmGeocoder = new L.Control.OSMGeocoder({
        collapsed: false,
        position: 'topright',
        text: 'Search',
        placeholder: 'Enter address',
        bounds: searchBounds,
        callback: function(results) {
            // add a message on the screen about not finding an address (future step)
            if (results.length == 0) {
	       console.log("ERROR: didn't find a result");				
	   }
            
            // clear previous geocode results
            addressSearchResults.clearLayers();
            
            // create icon for result
            var addressSearchIcon = L.AwesomeMarkers.icon({
                icon: 'map',
                prefix: 'fa',
                markerColor: 'orange',
                iconColor: '#fff'
             });
            
            // get coordinates for result
            var coords = L.latLng(results[0].lat,results[0].lon);
        
            // create a marker for result
            var marker = L.marker(coords, {
                icon: addressSearchIcon
            });
            
            // add result object to map and zoom to 
            addressSearchResults.addLayer(marker);            
            this._map.addLayer(marker).setView(coords,17);  
            
            // open pop-up for location
            var popup = L.popup({closeOnClick: true}).setLatLng(coords).setContent(results[0].display_name).openOn(map);
        }
    }).addTo(map);    

Try this code it's working with marker postion. <script type="text/javascript">
var markers = {};

function setMarkers(data) {
  data.BMS.forEach(function (obj) {
	if (!markers.hasOwnProperty(obj.id)) {
	  markers[obj.id] = new L.Marker([obj.lat, obj.long]).addTo(map);
	  markers[obj.id].previousLatLngs = [];
	} else {
	  markers[obj.id].previousLatLngs.push(markers[obj.id].getLatLng());
	  markers[obj.id].setLatLng([obj.lat, obj.long]);
	}
  });
}
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
var osm = new L.TileLayer(osmUrl, {attribution: osmAttrib});
var map = new L.Map('map').addLayer(osm).setView([48.5, 2.5], 15);

var searchBounds;
var osmGeocoder = new L.Control.OSMGeocoder({
	collapsed: false,
	placeholder: 'Search location...',
	bounds: searchBounds,
	callback: function (results) {
		var bbox = results[0].boundingbox,
		first = new L.LatLng(bbox[0], bbox[2]),
		second = new L.LatLng(bbox[1], bbox[3]),
		bounds = new L.LatLngBounds([first, second]);					
						
		if (results.length == 0) {
		   console.log("ERROR: didn't find a result");				
		}				
			
		var center = [results[0].lat, results[0].lon];
		console.log(center);
		var json = {
			  "BMS":[{
				"id": 'A',
				"lat": results[0].lat,
				"long":  results[0].lon,
				"text": "<h2>Hôtel Ibis 1</h2><a href='#'>view</a><p>Rte Nationale 250 1 imp Bosquet, 33260 L</p>"
			  }]
			}
		setMarkers(json);
		map.flyTo(center, 10);						
		this._map.fitBounds(bounds);
	}
});
map.addControl(osmGeocoder);				

</script>`