Skip to content

Instantly share code, notes, and snippets.

@chieft3ch
Created June 18, 2019 14:49
Show Gist options
  • Save chieft3ch/02372c9d2bde534abc0b510717ff7bae to your computer and use it in GitHub Desktop.
Save chieft3ch/02372c9d2bde534abc0b510717ff7bae to your computer and use it in GitHub Desktop.
Google maps GeoCode with Searchbar
<form action="" id="pointLookup">
<input type="text" name="location" id="location" required maxlength="255" minlength="3">
<button type="submit">Submit</button>
</form>
<div id="map-canvas" style="width:100%; height:400px;"></div>
<script>
var geocoder;
var map;
var places;
var markers = [];
function initialize() {
// create the geocoder
geocoder = new google.maps.Geocoder();
// set some default map details, initial center point, zoom and style
var mapOptions = {
center: new google.maps.LatLng(40.74649, -74.0094),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// create the map and reference the div#map-canvas container
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
// when page is ready, initialize the map!
//google.maps.event.addDomListener(window, 'load', initialize);
function fetchPlaces(lat, lng) {
var infowindow = new google.maps.InfoWindow({
content: ''
});
jQuery.ajax({
url: 'SOMEJSONURL',
data: {
'lat': lat,
'lng': lng
},
success: function (response) {
$('#map-canvas').show();
$.each(JSON.parse(response), function (index, value) {
tmpLatLng = new google.maps.LatLng(value.Latitude.replace(',', '.'), value.Longitude.replace(',', '.'));
// make and place map maker.
var marker = new google.maps.Marker({
map: map,
position: tmpLatLng,
title: 'name'
});
markers.push(marker);
});
}
})
};
jQuery("#pointLookup").submit(function (e) {
// get the location text field value
var loc = jQuery("#location").val();
geocoder.geocode({
'address': loc,
'region':'FR'
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
markers.push(marker);
// preparing data for form posting
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var loc_name = results[0].formatted_address;
console.log(results[0]);
// Get markers
fetchPlaces(lat, lng);
} else {
alert("Try again. Geocode was not successful for the following reason: " + status);
}
});
e.preventDefault();
return false;
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment