I'm slowly learning & building a map app, which will display a search term on a Google Map using the Google Geocoding API. My issue a present is that I am attempting to view what the search term is at the end of the onclick listener with a console.log (which I will then try to send to Google Geocoding API).
The issue that I'm having is that when I type characters into the search-name & click on the button, I get the console.log output, but at first click it is blank or the previous term if I click once. When I then click again, it displays the correct output.
Presumably, the onclick listener is using the cached term somehow?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
#map-canvas {
width: 100%;
height: 600px;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
</head>
<body>
<form id="search">
<p><input id="search-name" type="text" placeholder="Type Region Here"></p>
<p><input id="search-submit" type="submit" value="Search For Region"></p>
</form>
<p id="demo"></p>
<div id="map-canvas"></div>
<script type="text/javascript">
// Global Variables
var name;
//map options
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(37.09024, -100.712891),
panControl: false,
panControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: false
};
//Fire up Google maps and place inside the map-canvas div
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Button Click
document.getElementById("search-submit").addEventListener("click", function(){
// Search Submit
$(function() {
$("#search").submit(function(event){
event.preventDefault();
name = $("#search-name").val();
return name;
});
});
// console.log("Search term after search submit is: "+name);
console.log("Search term at end is: "+name);
});
</script>
</body>
</html>
EDIT:
For anyone interested in knowing how I fixed it, I did the following (as a separate .js file - but it would work within the script tags):
$(document).ready(function(){
//Map Options
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(37.09024, -100.712891),
panControl: false,
panControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: false
};
//Map Creation
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Search Submit
$("#search").submit(function(event){
event.preventDefault("", function(){
//
});
name = $("#search-name").val();
console.log("Search term at submit is: "+name);
return name;
});
});