Geocoding of addresses
SmartMaps can geocode addresses worldwide. In this example the individual components of an address are used for geocoding.
The example is complete; you can save it locally in a file and call it in the browser. You only have to replace the value for the apiKey
.
SmartMaps map
Code example: Geocoding of addresses
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Geocoding</title>
</head>
<body>
<div id="map-wrapper">
<div class="geocoder-form" style="z-index:1000">
<form id="location-form">
<fieldset>
<legend>Geocode address</legend>
<label>
Zip:
<input type="text" name="zip" value="76133" placeholder="zip code">
</label>
<label>
City:
<input type="text" name="city" value="Karlsruhe" placeholder="city">
</label>
<label>
Street:
<input type="text" name="street" value="Wattkopfstr" placeholder="street">
</label>
<input type="hidden" name="country" value="DE">
<button type="submit">send</button>
</fieldset>
</form>
</div>
<div id="map" style="height: 400px; width: 500px;"></div>
</div>
<!-- SmartMaps-API -->
<script src="https://www.yellowmap.de/api_rst/api/loader?libraries=free-3&apiKey={API_KEY}"></script>
<script>
ym.ready(function(modules) {
var geocodingForm = document.getElementById('location-form');
// Define Layer Group.
var layerGroup = ym.layerGroup();
// Draw map.
var map = ym.map("map", {
center: ym.latLng(49.021273, 8.439316),
zoom: 14
});
// Drawing a Layer Group.
layerGroup.addTo(map);
geocodingForm.onsubmit = function(e) {
e.preventDefault();
var inputs = document.querySelectorAll('#location-form input');
var zip = inputs[0].value;
var city = inputs[1].value;
var street = inputs[2].value;
var country = inputs[3].value;
// Adressdaten geokodieren.
modules.geocode({
"country": country,
"district": "",
"zip": zip,
"city": city,
"cityAddOn": "",
"cityPart": "",
"street": street,
"houseNo": "",
"singleSlot": ""
});
};
ym.services.geoCoder.on('success', function(req, res) {
// Delete old data from the card.
layerGroup.clearLayers();
var geoJson = ym.geoJson(res.body, {
// Draw markers for each entry.
onEachFeature: function(feature, layer) {
layer.setIcon(ym.provider.Icon.Default());
var popUpContent = "";
if (feature.properties.street) {
popUpContent += feature.properties.street + ", "
}
if (feature.properties.zip) {
popUpContent += feature.properties.zip + " "
}
if (feature.properties.city) {
popUpContent += feature.properties.city + " "
}
if (feature.properties.cityPart) {
popUpContent += feature.properties.cityPart
}
// Show address data in popup.
layer.bindPopup(popUpContent);
}
});
// Optimize map section for result set.
map.fitBounds(geoJson.getBounds());
layerGroup.addLayer(geoJson);
});
ym.services.geoCoder.on('error', function(req, res, errorType) {
console.log(arguments);
});
});
</script>
</body>
</html>