Geocoding displaying "ZERO_RESULTS" to every input - javascript

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>

Related

<script>Not Getting Lat and Long from the given map address jquery or javascript

I want to find lat and lng from given address but i cant find same can you please help me to solve this query
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "patan"}, function(results, status) {
alert(status)
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location.lat());
//$('.push-down').text("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng());
} else {
$('.push-down').text("Something got wrong " + status);
}
});
</script>
Kindly try below code :-
<div class="push-down"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "patan"}, function(results, status) {
//alert(status)
if (status == google.maps.GeocoderStatus.OK) {
var Lat = results[0].geometry.location.lat();
var Lng = results[0].geometry.location.lng();
$('.push-down').html("latitude: " + Lat + " <br/>longitude: " +Lng);
} else {
$('.push-down').text("Something got wrong " + status);
}
});
</script>
Hope it helps :)
Since your question is marked php as well, I would recommend using the Google Geocode API Web Service. I find it much easier to use, than the js API.
Here is an example code:
<?php
// Request URL for Google Geocode API, result type = json, language = hu-HU, region = hu-HU
// Change result type, language, region to your needs
define('REQ_URL', 'https://maps.googleapis.com/maps/api/geocode/json?language=hu&region=hu');
// Your Google API key goes here
define('API_KEY', 'your-google-api-key-goes-here');
// Address you want to geocode
// Needs to be url encoded
$address = 'address-you-want-to-geocode-goes-here';
$address = urlencode($address);
// Parsing full request url
$request_url = REQ_URL . '&address=' . $address . '&key=' . API_KEY;
// Query Google API for result
$response = file_get_contents($request_url);
$resp = json_decode($response, true);
// Result array
print '<pre>';
print_r($resp);
print '</pre>';
I hope, I could be of any help.

Reverse Geocoding to show address

I have a script which I can't get working. I keep getting the error 'Geocoder failed' but I am not sure why. It is supposed to get the long/lat and then reverse geocode it to show the street address in an alert box. I have tried ensuring that the browser is letting it share the location. I have also tried accessing via HTTPS as I read that this was needed now but it still doesn't work.
If anyone can help me to get this working I would be most grateful!
Thanks in advance.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Current Location Address</title>
<style>
</style>
</head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()"> <font face="verdana">
<!DOCTYPE html>
If available, your current address will have been displayed in a message window. Please press 'Back' when finished.
</body>
</html>
Your errorFunction is automatically passed an error parameter that you can take a look at:
function errorFunction(error){
alert("Geocoder failed: "+error.message);
}
See the MDN docs for more background and examples.

Trying to send data from JS to PHP with AJAX

I am trying send some data from JavaScript to PHP, but it seems I'm not doing it wrong. I am using reverse geocoding to get the location name of a specific marker on google maps, this works just fine. However, I need that particular data on the PHP-side.
This is what my script looks like, var markerLocation is the variable I'm trying to get across (js/map_article.js):
// Reverse geocoding
function geocodeLatLng(geocoder, map, infowindow)
{
result.forEach(function(entry) {
var latlng = {lat: parseFloat(entry.lat), lng: parseFloat(entry.lng)};
geocoder.geocode({'location': latlng}, function(results, status)
{
if (status === google.maps.GeocoderStatus.OK)
{
if (results[1])
{
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
var markerLocation = results[1].formatted_address;
// Send the adress back to php
$.ajax({
type: "POST",
url: 'article.php',
data: {markerLocation : markerLocation},
success: function(data)
{
alert("success!");
}
});
}
else
{
window.alert('No results found');
}
}
else
{
window.alert('Geocoder failed due to: ' + status);
}
});
});
}
And this is what the PHP (article.php) looks like:
<?php
$id = $_GET['id'];
$sql = "SELECT * FROM blog WHERE id=$id";
$result = db_select($sql);
?>
<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var result = <?php echo json_encode($result) ?>;
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript" src="js/map_article.js"></script>
<body>
<?php
// Is the AJAX-data coming across?
if(isset($_POST['markerLocation']))
{
echo "<p>".$_POST['markerLocation']."</p>";
}
else
{
echo "<p>It did not work..</p>";
}
?>
</body>
</html>
The Alert message "success!" does show, but the variable $_POST['markerLocation'] is still undefined. Where did I go wrong?

Why when I set address in displayAddress() does it display the address correctly in the map but still log "No address" in the console?

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);
}
});
}

Execute JavaScript code after $_POST request in php

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();
});
});

Categories