Require JS, Google Geocoding - same-origin Issue - javascript

What I'm doing and what I've tried
I'm using Google Geo coding web service to get the latitude and longitude of an address I pass, like this:
$.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address=Boston&sensors=true",function(data){
//Do my programming here
});
It was, for some reason working perfectly, initially, but then it stopped working and and I discovered this was the issue, that is using Google client side API.
I also read the answer on that SO question, which says the <script> tags help get over the cross site scripting issue.
My problem :
I'm using RequireJs, so I include the files like this :
var Google = require("http://maps.google.com/maps/api/js?sensor=false");
So, how do I get my Google API working again and how do I do that with requireJS

requirejs will load the Maps-API asynchronous, but the URL you have used cannot be used for asynchronous loading(see async loading javascript with document.write) .
What to do: add the callback-parameter to the URL to be able to load the Maps-API asynchronously and execute the google-maps-related code in a function with a name equal to the value of the provided callback-parameter.
function geocodeaddr(){
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': 'Boston' }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].geometry.location);
}
else {
console.log("Geocoding failed: " + status);
}
});
}
require(["http://maps.google.com/maps/api/js?sensor=false&callback=geocodeaddr"]);

Related

How do I pull data from an API in javascript?

I'm working on a little weather app project, but now that i've changed the code to make the long and lat change depending on you geo location, the button doesn't work. When i click it nothing happens, i can't even tell if the API is pulling the data. Here is my code as well as a codepen I made to fool around with.
http://codepen.io/lettda/pen/yaGaLx
$(document).ready(function(){
$("#reveal").on("click", function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
var long;
var lat;
var api = "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&appid=de61ccfbde0405f57d64dbb53323fccf";
$.getJSON(api, function(data){
$(".message").html(JSON.stringify(data))
});
});
};
});
});
open your developer tools (in chrome press F12) and have a look into the console:
pen.js:4 getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://.... for more details.
it's an simple cross origin problem

google js api reverse geocode wrong address from LatLng

I've got a real trouble trying to start my web app because of wrong adress returns from Google Geocoder when passing LatLng values to it.
http://jsfiddle.net/3kUx7/
geocoder.geocode({'latLng': latLong}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results) {
The main problem is that coordinates pair 50.393386951159684,30.612979531288147
returns the wrong address "улица Заречная, 9А"
The same pair tested in new and old google maps and even regular google search returns correct address "Днепровская наб., 26Г, Киев, город Киев 02000"
The code i use for reverse geocode is the same as in jsfiddle.
That area was newly built (5-7 years ago :) ) adn google has some wrong building on a regular map but address almost correct.
Reverse Geocoding Test App
http://reverse-geocoding.appspot.com/
gives the SAME WRONG RESULT but showing 2014 copyright!
I just don't understant what am i doing wrong. Or google has different DBs for online maps and JS API. if so GOOGLE PLEASE SYNCRONIZE! The world had changed for past 5 years!

Google Map Geocoding not returning lat/long for a valid complete address

I am facing a weird issue with Google Maps Geocoding API v3. It works fine for all other addresses that i have tried so far but it's giving me an issue with the following address.
35 & 36, Rajiv Gandhi Infotech Park, Pune, 411057, India
OR
Plot No 35/36,Rajiv Gandhi Infotech Park,Phase 1,MIDC,Hinjawadi,Pune,411057,India
Even for: Rajiv Gandhi Infotech Park, Pune, 411057, India
The GeocoderStatus is ZERO_RESULTS.
Below is the code snippet.
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address' : address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
....
}
else{...}
However, the same address is returning a valid lat/long with 'OK' status in json result at the below link.
http://maps.googleapis.com/maps/api/geocode/json?address=35&36+Rajiv+Gandhi+Infotech+Park,+Pune,+411057,+India&sensor=true
Can anyone please tell me what is the cause of this issue and its resolution?
Perhaps that particular address is recently added to Google's database.
Why do the Google Maps APIs Geocoders provide different locations than Google Maps?
The API geocoder and Google Maps geocoder sometimes use different data sets (depending on the country). The API geocoder occasionally gets updated with new data, so you can expect to see results changing or improving over time.
taken from: http://code.google.com/apis/maps/faq.html#geocoder_differences

Google Maps rendering locally but not in live environment

I have a page that renders a simple google map for a specified location. This map renders without any problems at all when I run it locally on localhost, however, when I deploy this code to our live web servers (using our LIVE google API key for the appropriate domain) it fails to render, and upon putting a series of alerts within the javascript on the page, it appears that the 'Initialize' method (which should be called within body onLoad) is not being called.
When I view the HTML source that is rendered on the live server it appears exactly as per the local version of the site (including the call to initialize() within the body onLoad event), albeit with the different maps API key.
I have output the host (alert(window.location.host);) to ensure that the key I generated via the google maps api site, corresponds exactly to the live server, which it does.
Does anyone have any ideas why it would be working locally but not when deployed to the live servers? The live site is hosted on 2 load-balanced web servers.
This is the javascript that is rendered:
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAA-BU8POZj19wRlTaKIXVM9xTz76xxk4yAELG9u79oXrhnLTB5NRRvAZ-bkKn1x8J68nfRTVOIWNPJEA" type="text/javascript"></script>
<script type="text/javascript">
var map;
var geocoder;
alert(window.location.host);
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("businessMap"));
map.setUIToDefault();
geocoder = new GClientGeocoder();
showAddress('St Margarets Street SW1P 3 London');
}
}
function showAddress(address) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
// Address could not be located.
jQuery('#googleMap').hide();
} else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
var html = 'Address info for the marker';
marker.openInfoWindow(html);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
}
}
);
}
</script>
Any help would be much appreciated.
Thanks.
I've located the problem. It was some conflicting javascript related to Facebook Connect that was calling an FB Connect related page on window.onload, therefore not calling the initialize function within the body onload event.
I should have noticed this conflicting javascript earlier!

Google Geocode via HTTP callback function?

I want to use the google geocode via HTTP functionality to translate a city name into longitude and latitude in for my AJAX web application.
However, it appears that no callback function exists for the HTTP geocoder functionality
http://code.google.com/apis/maps/documentation/geocoding/index.html
Is that true, no callback function exists?
Because if that is true, it essentially means that the Google geocode via HTTP api is useless when used with AJAX because JavaScript will throw a crossdomain exception error.
Any ideas on how I can use the geocode via HTTP api in my AJAX web application in JavaScript?
Note: I do not want to use the full blown Google Maps API which is approx 200kb download (i.e. GClientGeocoder). I want to use the HTTP api b/c of it's super quick responsiveness and lack of needing my web users from having to download the huge full blown interactive google maps api.
E.g.
http://maps.google.com/maps/geo?output=json&sensor=false&key={API_KEY}&q={CITY,STATE}&CALLBACK=????
Thanks
Here is an example that uses the Google Maps Geocoder. The geocoder function getLocation takes a callback function as the second argument.
function findAddress(street, city, state, zip) {
var address = [
street,
city.toLowerCase(),
state.toLowerCase(),
zip
].join(', ');
if (!geocoder) {
geocoder = new GClientGeocoder();
}
if (geocoder) {
geocoder.getLocations(
address,
function(result) {
var dialog, len, point;
if (result.Status.code != G_GEO_SUCCESS) {
alert("Error: "+result.Status.code)
} else {
len = result.Placemark.length;
if (len > 1) {
alert("Multiple matches were found. I'll leave it as an exercise to handle this condition");
} else {
point = new GLatLng(
result.Placemark[0].Point.coordinates[1],
result.Placemark[0].Point.coordinates[0]
);
}
}
}
);
}
}
hmm....I think you'd have to have your AJAX call back to your own server, and then call Google's Geocode from your server.
Thats how I do AJAX geocoding, it all goes through my ASP.NET code.
EDIT:
In the ASP.NET webforms environment I might implements this as a lightweight ASHX file, but for the purposes of simplicity, here's an ASPX example:
public partial class GoogleHandler : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
Response.Write(GetGoogleXML("http://pseudo_googlegeocode?parameter=" + parametersFromQuerystring);
}
}
In the example above, the .NET page is only passing the request along.
But in a real environment, I'd rather my .NET code do more than just pass the data over. This way I can do error handling, filtering, validation, business logic, all on the server, before sending that data over to the client.
Also, this allows for greater abstraction. i.e, I might change from google to yahoo geocoding. In this way I'd only have to change my serve logic, and leave the client to just receive a generic set of coordinates/location data.
Also, using that abstraction I could actually aggregate multiple data from various geocoding data sources. Again, the server takes care of aggregating, the client just receives and displays the filtered data.
As others noted, you didn't read the full page. You want what that page calls the JavaScript Client Geocode.
Here's a simplified version of a script I wrote a while back. It also uses a Google Map control, but feel free to ignore that. The delay function hack is because it seemed Google was occasionally returning null when I hit their servers too fast. I don't know if this is still an issue, so don't put it in unless you have to.
<script type="text/javascript">
//<![CDATA[
var freezeLocations;
var coder;
var map;
function load() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(38.479395, -98.349609), 4);
map.addControl(new GLargeMapControl());
}
coder = new GClientGeocoder();
missionLocations = new Array();
missionLocationsDelayed = new Array();
addMissionLocation("Atlanta, Georgia", "http://improveverywhere.ning.com/group/atlanta");
//etc.
}
function addMissionLocation(newLocation, url)
{
var successful = false;
var counter = 0;
while(!successful && counter < 3)
{
coder.getLatLng(
newLocation,
function(point) {
if (!point) {
//alert(newLocation + " not found");
successful = false;
} else {
missionLocations.push(new GMarker(point, { title:newLocation}));
//alert(missionLocations.length);
map.addOverlay(missionLocations[missionLocations.length - 1]);
missionLocations[missionLocations.length - 1].bindInfoWindowHtml("<a href='" + url + "'>" + newLocation + "</a>");
successful = true;
}
}
);
if(!successful)
{
delayGeocode();
}
counter++;
}
}
function delayGeocode()
{
for(var i = 0; i < 2000000; i++)
{
}
}
//]]>
</script>
You could use Yahoo Query language as outlined in my blog post http://jawtek.blogspot.com/2009/03/unwritten-guide-to-yahoo-query-langauge.html
You would be able to use a yql statement like: select * from json where
url="http://maps.google.com/maps/geo?output=json&sensor=false&q=Indianapolis,In"
Then you would add a script tag to your html (can be done with document.createElement('script')) with a src http://query.yahooapis.com/v1/public/yql?q={your yql here}&format=json&callback={your function here} where {your yql here} is replace with a URI Encoded version of you yql statment.
If you have looked at the
documentation and not found it and
both Andrew and Mike have not said
"yes", and told you how to do it, I
suspect you have your answer.
lol
and lets all read the service's documentation:
10.13 hide or mask from Google the identity of your service as it uses
the Service, including by failing to
follow the identification conventions
listed in the Maps APIs Documentation;
or
10.14 violate any policies in the Maps APIs Documentation or violate Google's
Software Principles (...)
Also
This service is designed for geocoding static (known) addresses
using a REST interface, for placement
of application content on a map. For
dynamic geocoding of user-defined
addresses (for example, within a user
interface element), consult the
documentation for the JavaScript
Client Geocoder or the Maps API for
Flash Client Geocoder. Geocoding is a
time and resource intensive task.
Whenever possible, pre-geocode known
addresses (using the Geocoding Service
described here or another geocoding
service), and store your results in a
temporary cache of your own design.
But then again you could try Google Maps API V3 Geocoder
Look at the Google Maps API. It has some functions with callback that uses it's geocoding service.
http://code.google.com/apis/maps/documentation/reference.html#GClientGeocoder.getLatLng
I second the suggestion to create a server-side page to access the geocoder. I am doing something similar and it works great. There's a good article about working with the geocoder in PHP here.
Also note that technically you're not permitted to use Google's geocoder unless you'll be displaying the data on a Google Map - but I don't know if they'll actually check on you.
I too encountered the challenges you described above. As you indicated, Google prevents cross-domain HTTP access to the Geocode API URL:
Same origin policy
JSONP and Google Maps API Geocoder - Not a Bug
This does severely diminish its usefulness when using client-side scripting. The only solution I found to this challenge was to create a server-side proxy service that relays the responses from the Google Maps Geocode API to my client-side script.
I wrote an extremely long-winded blog post describing this process.

Categories

Resources