I want to place a marker on a map with geocoding. I got a working code for that:
$(document).ready(function(){
$('#submit').click(function(){
var address = document.getElementById("address").value + ", CH";
geocoder.geocode(
{'address': address},
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,
title: 'Sie suchten nach:' + ' ' + address
});
}
else if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
window.alert = function(){}
}
else
{
alert("An unknown error occured. Refresh the page or contact the IT team! Error: '" + status + "'");
}
});
});
And I got this HTML form:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input type="text" id="address" name="address" placeholder="Enter a zip code" style="width:250px;" onkeypress='filterTextbox(event)' />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
If I hit submit it should send my request to the server with $_POST and then send me an answer. After that, I want to execute the JavaScript code. So I've done this:
<?php
if(isset($_POST['submit'])){
echo "<script>
$(document).ready(function(){
var address = document.getElementById('address').value + ', CH';
geocoder.geocode(
{'address': address},
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,
title: 'Sie suchten nach:' + ' ' + address
});
}
else if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
window.alert = function(){}
}
else{
alert('An unknown error occured. Refresh the page or contact the IT team! Error: '' + status + ''');
}
});
});
</script>";
}
}
?>
It sends me an answer (the page refresh because of the action) but then it does not execute the JavaScript code. The JavaScript code is for placing a marker at the place of what the users typed in the textbox. And it's working fine if I execute it "normal".
Hope you know what I mean
You have syntax errors
alert('An unknown error occured. Refresh the page or contact the IT team! Error: '' + status + ''');
should be
alert('An unknown error occured. Refresh the page or contact the IT team! Error: \'' + status + '\'');
Another likely cause is that the geocoder function has not yet been initialised by the time the document is ready.
Somewhere earlier on the page you should have code that looks similar to this:
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
geocoder = new google.maps.Geocoder();
}
You need to run your script at that point.
A way you can ensure that your script will be run is this:
// Where you load geocoder
var race_won = false;
var load_php_script = function() {
race_won = true;
};
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
geocoder = new google.maps.Geocoder();
load_php_script();
}
// Replace document.ready with this:
var php_script = function() {
// .. your old document ready code here ..
}
if (race_won) {
php_script();
}
else {
load_php_script = php_script;
}
Are you sure you have included jquery in the response? Are you sure that the element id="address" exists? Does browser's developer console report some error? Use breakpoints in it and see what's going on.
I understood that you try to update google maps when you push submit button. I don't see the neccessity of the form unless you want to save the addres in your database but then you should use ajax also.
If i'm right you should have this:
Explanation: when you press submit button will not refresh anymore the page and the address from input field will be send to the geocode function which will make an ajax call and at succes status == google.maps.GeocoderStatus.OK will execute the code from that if.
<div>
<input type="text" id="address" placeholder="Enter a zip code" style="width:250px;" onkeypress='filterTextbox(event)' />
<input type="button" id="submit" value="Submit" />
</div>
$('#submit').click(function(){
var address = document.getElementById('address').value + ', CH';
geocoder.geocode(
{'address': address},
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,
title: 'Sie suchten nach:' + ' ' + address
});
// save the address in database
$.ajax ({
url: "saveAddress.php",
data: {'address': address},
success: function() { //
alert("Should be saved in database");
}
});
}
else if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
window.alert = function(){}
}
else{
alert('An unknown error occured. ');
}
});
});
Use an ajax request and run your JS code after success of this request.
You are using jQuery so you can use:
$('#yourform-id').on('submit', function(event) {
$.ajax('/your/url/here', {
type: 'post',
data: { zipcode: $('#address').val() }
}).done(function() {
/* your JS code after successful request goes here */
});
event.stopPropagation();
}
EDIT: You can do this also without the ajax request. But the important thing is to register the .on('submit', function(event) { /* your geocode JS code here */ event.stopPropagation(); } event to your form so the form doesn't get sent.
The event.stopPropagation() stops your form from reloading the page and send the form data via HTTP. In earlier jQuery versions you returned false but this is deprecated now.
So add this code to the HTML file where your form is too:
$(function() { // on ready
$('#yourform-id').on('submit', function(event) {
var address = document.getElementById('address').value + ', CH';
geocoder.geocode({'address': address}, 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,
title: 'Sie suchten nach:' + ' ' + address
});
} else if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
window.alert = function(){}
} else{
alert('An unknown error occured. Refresh the page or contact the IT team! Error: '' + status + ''');
}
});
event.stopPropagation();
});
});
Related
I'm having an issue with trying to add an AJAX request to a google map as the title suggests. My web app currently allows a user to search a location which will return a marker to that location as well as the longitude and latitude of the location.
Essentially what I'm trying to do is pass the latitude and longitude variables calculated into a controller class in Spring MVC, and I'm attempting to do this via an AJAX request, however when I add the AJAX request to a JS function, and add this function to the onClick() of the "Locate" button the map disappears and the search functionality no longer works.
Is this happening because I'm reusing the $('.search_latitude').val(), and Long : $('.search_longitude').val() variables and the program is getting confused as to what I'm trying to do, or is it a case of my approach to the AJAX request is wrong?
Google Map JS code
<script>
var geocoder;
var map;
var marker;
/*
* Google Map with marker
*/
function initialize() {
var initialLat = $('.search_latitude').val();
var initialLong = $('.search_longitude').val();
initialLat = initialLat?initialLat:53.350140;
initialLong = initialLong?initialLong:-6.266155;
var latlng = new google.maps.LatLng(initialLat, initialLong);
var options = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("geomap"), options);
geocoder = new google.maps.Geocoder();
marker = new google.maps.Marker({
map: map,
draggable: true,
position: latlng
});
google.maps.event.addListener(marker, "dragend", function () {
var point = marker.getPosition();
map.panTo(point);
geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker.setPosition(results[0].geometry.location);
$('.search_addr').val(results[0].formatted_address);
$('.search_latitude').val(marker.getPosition().lat());
$('.search_longitude').val(marker.getPosition().lng());
}
});
});
}
$(document).ready(function () {
//load google map
initialize();
/*
* autocomplete location search
*/
var PostCodeid = '#search_location';
$(function () {
$(PostCodeid).autocomplete({
source: function (request, response) {
geocoder.geocode({
'address': request.term
}, function (results, status) {
response($.map(results, function (item) {
return {
label: item.formatted_address,
value: item.formatted_address,
lat: item.geometry.location.lat(),
lon: item.geometry.location.lng()
};
}));
});
},
select: function (event, ui) {
$('.search_addr').val(ui.item.value);
$('.search_latitude').val(ui.item.lat);
$('.search_longitude').val(ui.item.lon);
var latlng = new google.maps.LatLng(ui.item.lat, ui.item.lon);
marker.setPosition(latlng);
initialize();
}
});
});
/*
* Point location on google map
*/
$('.get_map').click(function (e) {
var address = $(PostCodeid).val();
geocoder.geocode({'address': address}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker.setPosition(results[0].geometry.location);
$('.search_addr').val(results[0].formatted_address);
$('.search_latitude').val(marker.getPosition().lat());
$('.search_longitude').val(marker.getPosition().lng());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
e.preventDefault();
});
//Add listener to marker for reverse geocoding
google.maps.event.addListener(marker, 'drag', function () {
geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('.search_addr').val(results[0].formatted_address);
$('.search_latitude').val(marker.getPosition().lat());
$('.search_longitude').val(marker.getPosition().lng());
}
}
});
});
});
geocoder.geocode({
'address': request.term,
componentRestrictions: {country: "ie"}
})
function loginAlert(){
alert("User must be logged in to view reports");
}
*************JS Function with the AJAX Request*************************
function sendLatLong(){
var Lat = $('.search_latitude').val();
var Long = $('.search_longitude').val();
$.ajax({
type: "POST",
url: "/latlong",
data: {
Lat : $('.search_latitude').val(),
Long : $('.search_longitude').val()
})
}
</script>
</head>
<body>
<h3>Area Rating System</h3>
//Some code omitted for brevity
<form>
<div class="form-group input-group">
<input type="text" id="search_location" class="form-control" placeholder="Search location"/>
<div class="input-group-btn">
<button class="btn btn-default get_map" type="submit" onClick() = "sendLatLong()">
Locate
</button>
</div>
</div>
</form>
<!-- display google map -->
<div id="geomap"></div>
<div id="forminputs">
<table>
<tr>
<!-- display selected location information -->
<th>
<h4>Location Details</h4>
<p>Address: <input type="text" class="search_addr" size="45"/></p>
<p>Latitude: <input type="text" class="search_latitude" size="30"/></p>
<p>Longitude: <input type="text" class="search_longitude" size="30"/></p>
<p style = "height: 120px"></p>
AJAX code snippet from the Google Map code above (included and highlighted above as well)
function sendLatLong(){
var Lat = $('.search_latitude').val();
var Long = $('.search_longitude').val();
$.ajax({
type: "POST",
url: "/latlong",
data: {
Lat : $('.search_latitude').val(),
Long : $('.search_longitude').val()
})
}
Server-side code in the controller class
#RequestMapping(value = "/latlong", method = RequestMethod.POST)
public #ResponseBody
String Submit(#RequestParam("Lat") String latitude,#RequestParam("Long") String longitude) {
// your logic here
System.out.println(latitude + "" + longitude);
return null; //I just want to print the latitude and longitude for now to show it has been sent to the serverside
}
I see that your button is inside a form and has a type as 'submit'.
type="submit"
This might be reloading the page and hence the map gets disappeared.
To make this request as completely asynchronous, the best possible solution would be to make the button as of type 'button'
type="button"
This will ensure that the form does not submits and you handle the submission using the AJAX 'submit' call.
Do that change and tell me in comments if the problem is still there. I'm just guessing it based on limited information.
It would also be helpful if you could share the console error log snippet along with this. Maybe that can also help.
I dont understand, how could this happen? I only got 1 variable but it seems like it has 2 different values. Please see the output below. Here's the code of the webpage:
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
var map;
var geocoder;
var center = new google.maps.LatLng(11.17840187,122.59643555);
var marker = new google.maps.Marker();
var info = new google.maps.InfoWindow();
var latitude = 0.00;
var longitude = 0.00;
var address = "NO ADDRESS";
var loaded = false;
function initialize() {
var mapProp = {
center : center,
zoom : 5,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
geocoder = new google.maps.Geocoder();
google.maps.event.addListener(map, "click", function (event) {
latitude = event.latLng.lat();
longitude = event.latLng.lng();
center = new google.maps.LatLng(latitude,longitude);
displayAddress();
moveToCenter();
console.log("Address : " + address)
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function moveToCenter(){
map.panTo(center);
marker.setPosition(center);
marker.setMap(map);
}
function displayAddress(){
geocoder.geocode( {'latLng': center},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
address = results[0].formatted_address;
}
else {
address = "";
}
info.setContent("<b>" + address + "</b>");
info.open(map,marker);
}
});
}
function setWidth(width){
document.getElementById('googleMap').style.width = width + "px";
google.maps.event.trigger(map, 'resize');
}
function setHeight(height){
document.getElementById('googleMap').style.height = height + "px";
google.maps.event.trigger(map, 'resize');
}
</script>
<style>
body
{
padding : 0;
margin : 0;
overlow : hidden;
}
#googleMap
{
width : 600px;
height : 600px;
overlow : hidden;
}
</style>
</head>
<body>
<div id="googleMap"></div>
</body>
</html>
I have a variable address in my code, but I dont understand why it has two different values. How does this happen? Is it a Javascript Bug?
Here's the output:
I see what you're asking now. Perhaps we can we rephrase the question.
Q: Why when I set address in displayAddress() does it display the address correctly in the map but still log "No address" in the console?
A: It's because you've introduced an asynchronous process into your code.
You think that the following should happen:
Set address to "No address"
Call displayAddress() which changes the value of address and
also displays it on the map
Log the changed address
What's actually happening is this:
Set address to "No address"
Call displayAddress() - the async process geocode starts
Log the address (this hasn't changed)
The async operation completes and the address is displayed on the map.
If you want to know more about async processes and how to return values from them this SO question has lots of relevant information.
I think the problem comes from the fact that the code which modifies your address variable is called after the console.log instruction.
As a matter of fact, all of the following code:
if(status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
address = results[0].formatted_address;
}
else {
address = "";
}
info.setContent("<b>" + address + "</b>");
info.open(map,marker);
}
is contained in the callback function which is passed to the geocoder.geocode method, and which will then be executed once the remote request has been completed. Which, given the reponse time of the remote request (a few tens or hundreds of miiliseconds), occurs after the execution of the console.log statement.
Take a closer look at your code.
function displayAddress(){
geocoder.geocode( {'latLng': center},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
address = results[0].formatted_address; <------ Take a look at this
}
else {
address = "";
}
info.setContent("<b>" + address + "</b>");
info.open(map,marker);
}
});
}
A form in an html file passes an input called "address" to a php file "registerEvent.php" where it is to be geocoded. No matter what address is inputted, the function still outputs ZERO_RESULTS status in an alert which can happen if the inputted address is invalid(i.e. NULL or an impossible address). I have tested, that recieving the address value from the html form works correctly both in php and at the start of the codeAddress() function.
<?php
$geoadrese = $_POST['address'];
?>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
geocoder = new google.maps.Geocoder();
var inputLat;
var inputLng;
function codeAddress() {
var address = '<?php echo $geoadrese; ?>';
// everything works fine up until this point
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
inputLat = results[0].geometry.location.lat();
inputLng = results[0].geometry.location.lng();
window.location.href = "registerEvent.php?inputLat=" + inputLat + "&inputLng=" + inputLng;
} else {
alert('Geocode was not successful for the following reason: ' + status);
};
});
}
codeAddress();
</script>
I have the following code below that geocodes address from a google spreadsheet. I have research this but I can't find a good example of how to just geocode postal codes in the US. Does anyone know a good example.
Thanks
function geocode(address) {
var response = UrlFetchApp.fetch("http://maps.googleapis.com/maps/api/geocode/json?address="+escape(address)+"&sensor=false");
var respObj=Utilities.jsonParse(response.getContentText());
var loc = {lat:NaN,lng:NaN};
try {
loc = respObj.results[0].geometry.ZIP_CODE
} catch(e) {
Logger.log("Error geocoding: "+address);
}
return loc;
}
https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple?csw=1
Try putting in a zip code it works.
This is the relevant code
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, 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
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
I am getting the following error:
Uncaught Error: Invalid value for property <address>:
Following is the code that does the geocoding:
function codeAddress(zipcode){
var address = zipcode;
alert("Address is: " +address);
geocoder.geocode( { 'address': address}, 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
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
The function takes a parameter 'zipcode' from the following code:
<input type="button" value="Geocode" onclick="codeAddress(<%=resultset.getString(3)%>)">
Please help me on this.
Make sure that the rendered onclick="codeAddress(<%=resultset.getString(3)%>)" actually has a string being passed to codeAddress(). You may have to add single quotes inside of that: onclick="codeAddress('<%=resultset.getString(3)%>')"