I'm trying to use Google Reverse Geocoding, which takes some coordenates and returns a JSON structure with some addresses. My javascript code is like this:
$.getJSON("http://maps.google.com/maps/api/geocode/json?",
{ latlng: myDevice.Lat + "," + myDevice.Lon,
sensor: true},
function (data) {
...
}
)
However, when debugging with firebug, when it gets in the function, it turns out that data is null.
Could someone give me any advice?
Thank you!
You are likely bumping up against the Same-Origin Policy. You have two choices:
Create a server-side proxy to grab the data, then request it via AJAX.
Use the Google Maps API
Related
Currently i am loading a carto Table containing polyogns to my map on a php file using catro.js and the key is visible in javascript. Example given below is to call the sql api.
var layerStyle = $('#landuse-style').text();
cartodb.createLayer(CartoDbLib.map, {
user_name: 'sandyjones',
type: 'cartodb',
sublayers: [{
sql: "SELECT * FROM master " + query,
cartocss: layerStyle,
}],
extra_params: {
map_key: "myAPiKey"
}
}
how to hide this api key on my server using proxy php file or a backend php file if you can suggest a code example that i can use.
sometime back i tried but i was stuck with a problem that in the url of images from carto server will contain the map key.
I'm afraid you would need to create your own proxy. Here is a node.js-based proxy as sample: https://github.com/CartoDB/cartodb-api-proxy , but this is not supported code and probably it is even outdated.
If your table data is anyway public (and it will be public - via proxy also), then I'd define the table as "Public" in Carto web, then your app does not need to put API key to the request at all.
I am making a mobile app with Phonegap and using Wordpress as a backend. I am using Advanced Custom Fields with a Google Maps post field which returns a PHP object to the app using JSON API. My Wordpress backend sends a normal JSON object to the app, but inside that object is where a stringified PHP object is returned.
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress). I have looked at other answers that say to use json_encode for this but my problem is that the app is just HTML/Javascript and no PHP. Is there a way to use PHP code in the middle of a Javascript function to do this? Or would it be better to change the backend so that it returns a JSON object instead of a PHP object in the first place? If so, how do I do that?
My experience in PHP is still somewhat limited so any help is appreciated.
edit: To clarify a bit more, I am using Wordpress on a separate domain from my Phonegap app and only using the JSON API plugin on the Wordpress end. I am then using jQuery Ajax calls to retrieve data from the Wordpress backend.
Also the returned PHP object looks like this: a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}
Another way I just thought of as well, would it be possible to just leave it as a PHP object and still read out the values from it somehow? I don't NEED it to be a JSON array, I just need a way to read the individual elements in the array in one way or another.
Here is also a tiny snippet of the JSON returned to clarify what I'm talking about.
"custom_fields": {
"location": [
"a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}"
]
}
That of course isn't the entire JSON object but it gives you an idea of what I'm dealing with.
I know you have a solution that works on the front end, but I still think it'd be better to fix this on the server.
Based on our conversation in the comments, I've had a closer look the code in the WordPress forum. The problem seems to be that the location field is an array of strings, not just a string. maybe_unserialize (and is_serialized, which it uses) don't handle arrays. Here's the updated code, which you should be able to drop into your theme's functions.php. I did a quick test, and it works for me.
class unserialize_php_arrays_before_sending_json {
function __construct() {
add_action( 'json_api_import_wp_post',
array( $this, 'json_api_import_wp_post' ),
10,
2 );
}
function json_api_import_wp_post( $JSON_API_Post, $wp_post ) {
foreach ( $JSON_API_Post->custom_fields as $key => $custom_field ) {
if (is_array($custom_field)) {
$unserialized_array = array();
foreach($custom_field as $field_key => $field_value) {
$unserialized_array[$field_key] = maybe_unserialize( $field_value );
}
$JSON_API_Post->custom_fields->$key = $unserialized_array;
}
else {
$JSON_API_Post->custom_fields->$key = maybe_unserialize( $custom_field );
}
}
}
}
new unserialize_php_arrays_before_sending_json();
If you're using a JSON API to retrieve the data, then why don't you deliver the data in JSON format to your app? Otherwise you seem to remove much of the point of using an API in the first place... You could of course parse that string in JavaScript if you really want to but that's a very ugly and error prone solution.
The JSON API plugin does seem to use JSON:
https://wordpress.org/plugins/json-api/screenshots/
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress).
This bit here leaves me confused. You do not have PHP objects on the client-side, PHP is a back-end technology. What is returned to the client is a string which can be HTML, XML, JSON, plaintext on any other form of encoding.
That said, saying you have an object $obj in PHP, you could pass it to your front-end application creating an end-point retrieve_object.php and in there:
echo json_encode($obj);
So long as that is the only thing your are outputting, you lient-side app can make a request (Eg: AJAX) to retrieve_object.php and get the json object.
BUT , and this is important (!) in doing so you serialize object properties. You will lose any PHP object method. If any object property is an object itself (EG: A DB Connection) then this will be lost too.
Hope this helps!
Has anyone noticed that google maps geocoding have changed the variable name of the lat and lng from, Qa and Ra to Pa and Qa.
Does anyone know a reason for this?
Edit: If you're using the Google Maps Geocoding Service, as #hamczu suggests, then you should be getting the results like this:
{
... snip ...
geometry: {
location: LatLng,
... snip ...
}
}
It sounds like you're not using the API methods for the LatLng object, but are instead trying to use its undocumented properties. Your question demonstrates one of the best reasons why this is a Bad Idea - the Google code is compressed and obfuscated, using short, arbitrary variable and property names, and Google may recompress its code at any time, arbitrarily changing these names. What it won't change is the function and attribute names in the published API - that's the whole point of having an API to begin with, and the reason why developers should code against the API, not the "undocumented features" of the currently available code.
So the best approach is to use the documented methods:
var lat = result.geometry.location.lat();
var lng = result.geometry.location.lng();
Otherwise, your code will likely break every time Google recompresses its code.
This question already has answers here:
Get only country specific result using google geocode api
(4 answers)
Closed 5 years ago.
I'm having problems telling the Google maps API to restrict the results from the geocoding service to a specific region.
A simple example reproducing the problem is here: http://jsfiddle.net/pqZGr/
The JavaScript code is really simple:
$(document).ready(function () {
var geocoder = new google.maps.Geocoder();
$("#name").autocomplete({
source: function (request, response) {
geocoder.geocode({ 'address': request.term, 'region': 'it' }, function (results, status) {
response($.map(results, function (item) {
return {
value: item.formatted_address
}
}));
})
}
});
});
I also specified the API URL as http://maps.google.com/maps/api/js?region=it&language=it&sensor=false besides the 'region': 'it' in the request.
The problem is the addresses returned by Google are not restricted (nor hinted) to Italy
For example if you search mil (the begininning of Milano) I get Circondario di Miltenberg, Germania and Milion, Alemdar Mh., 34122 Istanbul/Provincia di Istanbul, Turchia and reka Mil', Sacha-Jacuzia, Russia.
It's returning results (also, only three?) from all over the world, an nothing from Italy (even when there are multiple cities matching mil).
What am I doing wrong?
As a side note, is it possible to restrict the search only to the cities, and not to full addresses?
Thanks in advance.
It sounds like you really should be using the Google Places Autocomplete API standalone or built in to the Google Maps API.
The geocoding service isn't designed for autocomplete queries, and won't return the kind of results you're looking for. The region parameter is a hint like you said, but it's not a restriction so if there is no suitable "mil" in Italy, or there is a much better match elsewhere you'll get those results.
There's no way to restrict the results to just cities.
If you are using Google geocoder autocomplete with jQuery UI, you can edit one line in ui.geo_autocomplete.js, line 46, and add your region. It's not 100% precise, but will reduce the number of found addresses:
this.options._geocoder.geocode({'address': _address}, function(_results, _status)
Replace with:
this.options._geocoder.geocode({'address': _address + ' YOUR_REGION_HERE'}, function(_results, _status)
I am using the following method to reverse geocode a google maps latlng:
[GClientGeocoder.getLocations(address:String, callback:function)][1]
Which states as follows:
As this method requires a call to a Google server, you must also pass a callback method to handle the response. This response will contain a Status code, and if successful, one or more Placemark objects.
Can anyone point me to a definitive reference of what a Placemark object is as it seems to return different attributes for different locations. e.g. sometimes I get a ThoroughfareName and others an AddressLine. I would like to understand if I will always get one or other of them and whether they are interchangeable.
This page is from the Google Maps API documentation, and contains a pretty straightforward explanation of what a Placemark object is.
However, the part you probably want to focus on is where it states what format Google uses for the AddressDetails object in a Placemark, which is xAL (eXtensible Address Language). There is a link to the spec there, which leads to a downloadable schema (xsd file), which essentially defines the entire format. A word of warning: the spec is pretty extensive, but you may not need to worry about a great deal of it for your project.
EDIT:
Apologies for not being allowed to add links to the relevant pages for you.
You have to hunt for it, but Google does in fact have some documentation about Placemarks hidden away.
The contents of the Placemark object do vary based on the data available. I found the best way to work out what I was getting back was to use JSON.stringify to examine the response (for debugging):
function onGeocode (resp)
{
document.getElementById("cd_output").innerHTML = JSON.stringify (resp);
}
This gave me the following results when I GeoCoded an address in Sydney, Australia:
Placemark
{
id, address,
AddressDetails
{
Country, CountryNameCode, CountryName,
AdministrativeArea
{
AdministrativeAreaName,
Locality
{
LocalityName
Thoroughfare { ThoroughfareName }
PostalCode { PostalCodeNumber }
}
}
}
Accuracy,
ExtendedData
{
LatLonBox { north,south,east,west }
Point { coordinates }
}
}