Error while doing Geocoding using Google Maps API - javascript

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)%>')"

Related

(Google Map API) Geocode was not successful for the following reason: REQUEST_DENIED

I am new to this place and I desperately need help from experts here! D=
I tried to make a page that can generate dynamic numbers of google map. The webpage, however, keep showing Geocode was not successful for the following reason: REQUEST_DENIED.
I double checked my google API console and confirmed that the geocoding API and Javascript API are enabled. (I literally enabled all Google map API in the list...)
My Google Map API List
Can someone please take a look and tell me why? T_T
//------------------------------------------------\\
Below is my javascript and html button:
Javascript:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=APIkey&callback=initMap"
type="text/javascript"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=mapAddress"
type="text/javascript"></script>
<!-- &callback=mapAddress -->
<script>
function mapAddress(mapElement, address) {
var geocoder = new google.maps.Geocoder();
// alert(mapElement);
// alert(address);
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = {
zoom: 17,
center: results[0].geometry.location,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
HTML(Supposed to be php variable):
<button type="button" class="button_mapAPI" id="address_<?php echo $case["id"]; ?>" value="<?= $case['location_detail'] ?>" onclick="mapAddress('map1', 'Hong Kong')"/>Map Refresh</button>
Did you enable the Billing for API Key? Google Maps is no longer free. You have to associate a credit card so that you can get billed if your site has requests that exceed the $200 credit they give you monthly for free.
First of all, the problem was loading the scripts as async, remove it..
try that jsfiddle with your API KEY
(function(){
let mapElement = 'map';
let address = 'SPAIN';
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = {
zoom: 17,
center: results[0].geometry.location,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
})();
#map {
width: 100%;
height: 350px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY" type="text/javascript"></script>
<div id="map"></div>
Nead to enable geocoding api that convert address to coordinates and it is a bit pricier, use coordinates instead of address and no need for Geocoding API

How to use the JavaScript API V3 Client Geocoder to geocode postal codes

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

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

How do import a CSV file into the javascript for a webapp so that i can place address markers on a google maps canvas?

So I am a bit new to javascript and the Google maps API's. Currently I can place a marker given a single hard coded address variable called codeAddress.
codeAddress("99362");
function codeAddress(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 problem is that I need to be able to place multiple markers based on location and need to be able to parse address data from a CSV file or from an sql database.
thanks for the help.
I've used the jquery-csv plugin to process csv files.
If you can give more specifics on where this csv file is coming from, and how it will be loaded, I can give info on how you can convert this into a javascript array. Will this file be on the server already? If so, then it would make more sense to do some server side processing to read the file.
The following shows how to modify your code to work with an array of multiple addresses:
var addresses = ["99362", "01010", "12345"];
jQuery.each(addresses, function(index, address) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// we only need to center the map the first time
if (index == 0)
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);
}
});
})

Get or set google geocode maps in iframe src via javascript

I need to use Google maps v3 "GeoCode" dynamically.
i.e. I need to call / use a JS function from my php code (which generates storeDetail in a foreach loop ex dbase), from the src= attribute of an IFrame.
what I have done is not working....appreciate help with this.
I have: (in my db for each loop, with some other tr td stuff)
<tr><td rowspan='10' width='100' valign='top' height="150">
<iframe src="="<script>document.write(codeAddress(<?=$row->BrAddress;?>));</script>">"
name="<?=$row->BrAddress;?>" id="<?=$row->BrAddress;?>" scrolling="no" bgcolor="#fffff"> </iframe></td></tr>
and my Js is
var geocoder;
var map;
function codeAddress(address)
var myOptions = {zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP};
//each IFrame has the name ex db BrAdress field, "<?=$row->BrAddress;?>"
map = new google.maps.Map(document.getElementById(address + ",SouthAfrica"), myOptions);
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);
}
});
}

Categories