How to capture a json Web Service Request to a variable

352 views
Skip to first unread message

ron1776

unread,
May 27, 2010, 6:22:55 PM5/27/10
to Google Maps JavaScript API v3
I can't find documentation on how to capture the reply from Web
Service Request.

We want to set the json return array to a variable so we can parse the
map data we need to then build the cost to make a map.

Ideas?

- Ron

pete

unread,
May 27, 2010, 7:23:00 PM5/27/10
to Google Maps JavaScript API v3
Hi there,

Whilst capturing a web service request and parsing it's data is not a
Google Maps API related question, I'll attempt to answer as best as
possible for your current query.

Firstly, using a framework like JQuery makes this task extremely
simple, with their $.getJSON method. For documentation see:
http://api.jquery.com/jQuery.getJSON/

You can then write some code to fetch the feed, and store it in a
"data" variable

$(document).ready(function() {
$.getJSON("http://localhost/myService.aspx, function(data) {
parseMarkerList(data); //data = JSON returned
});
});

Your parseMarkerList(data) function can then loop through the JSON
returned, and pull out nodes such as Latitude, Longitude etc,
something such as:

function parseMarkerList(data) {
for (var i=0; i < data.length; i++) {
var lat = data[i].Latitude; // Where Latitude is the node name
var lng = data[i].Longitude; // Where Longitudeis the node
name
createMarker(lat, lng);
}
}

The createMarker function can then be a simple function that drops
markers on the map, see:
http://code.google.com/apis/maps/documentation/javascript/examples/marker-simple.html

Hope this has helped you.
The key is passing your data object from the request's response, to
the function that will iterate through the feed.
Using this technique you can drop hundreds of markers with no
additional code.

Cheers
Pete

Ron Calzone

unread,
May 28, 2010, 10:59:40 AM5/28/10
to google-map...@googlegroups.com, petej...@gmail.com
Pete,

Thank you for your kind answer and patience with my ignorance of the
finer aspects of Javascript!

I have spent several hours trying to work this out and am getting
nowhere. I have a time-sensitive project, so I need to ask for more help.

Why doesn't the following work? Is it necessary to specify another page
for the return json, or can a script on the same page process it?

Thanks!!!

- Ron


<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {

$.getJSON("http://maps.google.com/maps/api/geocode/json?address=201+W+Capitol+Ave,+Jefferson+City,+MO,+651011&sensor=false",

function(data) {
parseMarkerList(data); //data = JSON returned

alert(data);
});
});
</script>

<script>


function parseMarkerList(data) {
for (var i=0; i < data.length; i++) {
var lat = data[i].Latitude; // Where Latitude is the node name
var lng = data[i].Longitude; // Where Longitude is the node name

//createMarker(lat, lng);
}
}
</script>
</head>

<body>
<script>
alert("Lat: " + lat +"Lng: " + lng);
</script>


</body>
</html>

--

*************************************
Ron Calzone
Director, Missouri First, Inc.
mailto:r...@mofirst.org
Web URL http://www.mofirst.org
*************************************

Jason Sanford

unread,
May 28, 2010, 11:44:52 AM5/28/10
to google-map...@googlegroups.com
It looks like the data returned is an object and not an array. so when you say "for (var i=0; i < data.length; i++) {" there is no length property of the data object. Instead you should try "for (var i=0; i < data.results.length; i++) {" which is, I assume, an array of potential geocoding results.

Also, it looks like you're declaring your "lat" and "lng" variables inside a loop. If you do it this way they won't be accessible outside of the loop. Try declaring "lat" and "lng" outside of the loop and setting them inside. Kind of like this:
<script>
var lat; //Declare here
var lng;

function parseMarkerList(data) {
 for (var i=0; i < data.length; i++) {
       lat = data[i].Latitude; // Where Latitude is the node name //Set here

       lng = data[i].Longitude; // Where Longitude is the node name
       //createMarker(lat, lng);
   }
}
</script>


--
You received this message because you are subscribed to the Google Groups "Google Maps JavaScript API v3" group.
To post to this group, send email to google-map...@googlegroups.com.
To unsubscribe from this group, send email to google-maps-js-a...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-maps-js-api-v3?hl=en.


Ron Calzone

unread,
May 28, 2010, 1:05:37 PM5/28/10
to google-map...@googlegroups.com
Jason,

Thanks for the tips.   Something is still wrong, though.

I placed an alert in the function, to see if it being called and I get nothing.   ------------>>>>>>>>>>>>>  See below.

I was under the impression  from the jquery documentation that  $(document).ready(function() ran automatically without being called...?

Thanks!!

- Ron


$(document).ready(function() {
   $.getJSON("http://maps.google.com/maps/api/geocode/json?address=201+W+Capitol+Ave,+Jefferson+City,+MO,+651011&sensor=false", function(data) {
 parseMarkerList(data); //data = JSON returned
 alert(data); //-------------------->>>>>>>>>>>>>>> Test to see if function is called.
   });
});
</script>

<script>
var lat;
var lng;
function parseMarkerList(data) { 
 for (var i=0; i < data.results.length; i++) {

        lat = data[i].Latitude; // Where Latitude is the node name
        lng = data[i].Longitude; // Where Longitude is the node name
        alert(lat + " -- " + lat);    //-------------------->>>>>>>>>>>>>>> Test to see if function is called.

        //createMarker(lat, lng);
    }
}
</script>

William

unread,
May 28, 2010, 4:36:29 PM5/28/10
to Google Maps JavaScript API v3
On May 29, 12:59 am, Ron Calzone <r...@mofirst.org> wrote:
> Why doesn't the following work?  
>
> $.getJSON("http://maps.google.com/maps/api/geocode/json?address=201+W+Capitol+Av...",

due to browser security restrictions, you can only capture data from
JSON that originates from the same server as your HTML page. To get
around this "cross domain" security restriction requires a service
that supports JSONP, a format which includes a callback function name
in the request. For example Flickr and Twitter offer JSONP
services.

In the Maps API, Google have provided objects to access their web
services. You access the Google Maps API geocoding service within
your code via the google.maps.Geocoder object.

http://code.google.com/apis/maps/documentation/javascript/services.html#Geocoding

...

Ron Calzone

unread,
May 28, 2010, 7:26:23 PM5/28/10
to google-map...@googlegroups.com
The following method is right our of the geocode deveoper's guide See:
http://code.google.com/apis/gdata/docs/json.html

What's more, if you copy this to your browser and run it, it will return
json. My only problem is doing all of that in PHP or JS so I can
capture the json to a variable and parse out the lat-lgn.

http://maps.google.com/maps/api/geocode/json?address=201+W+Capitol+Ave,+Jefferson+City,+MO,+651011&sensor=false

I would be glad to use any other geocode system, though, if any can
suggest one.....

Thanks!

- Ron

Rossko

unread,
May 28, 2010, 8:44:38 PM5/28/10
to Google Maps JavaScript API v3
> What's more, if you copy this to your browser and run it, it will return
> json.  My only problem is doing all of that in PHP or JS so I can
> capture the json to a variable and parse out the lat-lgn.

At its most basic, I would have thought you just need to put these
together
http://uk2.php.net/manual/en/function.file-get-contents.php
http://webhole.net/2009/08/31/how-to-read-json-data-with-php/

Here's a more sophisticated example - it uses AJAX search API, just
substitute geocoding
http://dev-tips.com/featured/php-tip-add-custom-google-search-results-to-your-site-with-php

ron1776

unread,
May 30, 2010, 5:04:50 AM5/30/10
to Google Maps JavaScript API v3
I ended up using a PHP solution. Like a lot of PHP, it uses multiple
files - two besides the file with the login form.

MapFunctions.php is for invoking various map maintenance tools,
including login and requesting a Google token. It calls
GoogleLog1.php, which sets up the URL call Google requires for a token
request. GoogleLog1.php calls the Google Login where the token is
issued and then redirects to GoogleLog2.php which converts the single
use token into a session token and then returns the user to the
MapFunctions.php (or any other page of your choosing).

This is not elegant, but it didn't create dependencies on various
libraries I might lose track of over the years. The code follows:

MapFunctions.php
--------------------------
<?php
if (!isset($_SESSION)) {
session_start();
$token = $_SESSION['MM_token'];
}
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Google Map Functions</title>
<?php
function variousfunctions()
{
echo "This page is for invoking various map tools.";
echo "<br><br>";
}
?>

</head>

<body>
The Google Token is:
<?php
print $token;
print "<br><br>";
?>
<form name="form1" method="post" action="GoogleLog1.php">
Login to Google:
<label>login_google
<input type="submit" name="login_google" id="login_google"
value="Submit">
</label>
</form>
</p>
</body>
</html>


GoogleLog1.php
-----------------------
<?php
if (!isset($_SESSION)) {
session_start();
$token = $_SESSION['MM_token'];
}
?>
<?php
//Request a single-use authentication token from Google
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
$nextUrl = 'http://www.mysite----------------/GoogleLog2.php'; //
Change this to your site.
$scope = 'http://maps.google.com/maps/feeds/maps/';
$secure = 0; // set $secure=1 to request secure AuthSub tokens
$session = 1;
$authSubUrl = Zend_Gdata_AuthSub::getAuthSubTokenUri($nextUrl,
$scope, $secure, $session);
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Get a Google Token</title>
</head>

<body>
Fetching Token From Google
<script type="text/javascript">
var authurl = "<?= $authSubUrl ?>";
location.href = authurl;
</script>
</body>
</html>


GoogleLog1.php
-----------------------
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<?php
$singleUseToken = $_GET['token']; // This is the single use
token
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
$sessionToken =
Zend_Gdata_AuthSub::getAuthSubSessionToken($singleUseToken); //Make
the token a session token, not just for one use.
$tokenInfo =
Zend_Gdata_AuthSub::getAuthSubTokenInfo($sessionToken); //Retrieve
information about the session token
$_SESSION['MM_token'] = $sessionToken; // Set a session variable so
the token is portable.
?>
<script>
location.href = 'MapFunctions.php'; //Return to where you started
</script>

ron1776

unread,
May 30, 2010, 5:21:13 AM5/30/10
to Google Maps JavaScript API v3
Oops! My last post on this thread was for a related but different
problem. The following is how I ended up using PHP to read and parse
the json array returned from a Geocode web service request.

<?php
//This code builds a geocode query from an address, issues the query,
reads the json result into a variable which is then parsed into
address components and the Latitude and Longitude of that address.
$postdata = http_build_query(
array(
'var1' => '',
'var2' => ''
)
);

$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-
urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);

$Street_no = '1600 ';
$Street = ' Pennsylvania Ave ';
$City = 'Washington ';
$State = 'DC';
$Zip = '';
$jsonStreet_no = str_replace(" ", "+", (str_replace(" ", " ",
trim($Street_no)))); //Replace spaces with +
$jsonStreet = str_replace(" ", "+", (str_replace(" ", " ",
trim($Street))));
$jsonCity = str_replace(" ", "+", (str_replace(" ", " ",
trim($City))));
$jsonState = str_replace(" ", "+", (str_replace(" ", " ",
trim($State))));
$jsonZip = str_replace(" ", "+", (str_replace(" ", " ",
trim($Zip))));

$address_string = $jsonStreet_no . '+' . $jsonStreet . ',+' .
$jsonCity . ',+' . $jsonState . ',+' . $jsonZip;
$geocode_string = "http://maps.google.com/maps/api/geocode/json?
address=" . $address_string . "&sensor=false";
print 'geocode_string: ' . $geocode_string;
$result = file_get_contents($geocode_string, false, $context);

?>
<?php
echo "<br>";
?>
<?php
//echo 'Results: ' . $result;
echo "<br>";
?>

<?php
print '<u><b>Here are the parsed results:</B></u>';
echo "<br>";
$json_a = json_decode($result, true); //The 'true' parameter returns
an array. W/O it an object is returned so use -> to deconstruct the
object
print 'Status: ' . $json_a['status'];
echo "<br>";
print 'Results formatted_address: ' . $json_a['results'][0]
['formatted_address'];
echo "<br>";
print 'Results address_StreetNO: ' . $json_a['results'][0]
['address_components'][0]['long_name'];
echo "<br>";
print 'Results address_Street: ' . $json_a['results'][0]
['address_components'][1]['long_name'];
echo "<br>";
print 'Results address_City: ' . $json_a['results'][0]
['address_components'][2]['long_name'];
echo "<br>";
print 'Results address_State: ' . $json_a['results'][0]
['address_components'][5]['short_name'];
echo "<br>";
print 'Results address_Zip: ' . $json_a['results'][0]
['address_components'][7]['long_name'];
echo "<br>";
print 'Results address_County: ' . $json_a['results'][0]
['address_components'][4]['long_name'];
echo "<br>";
print 'Results geometry Latitude: ' . $json_a['results'][0]['geometry']
['location']['lat'];
echo "<br>";
print 'Results geometry Longitude: ' . $json_a['results'][0]
['geometry']['location']['lng'];
echo "<br>";
print 'Results geometry location_type: ' . $json_a['results'][0]
['geometry']['location_type'];
echo "<br>";
$coords = $json_a['results'][0]['geometry']['location']['lat'] . ',' .
$json_a['results'][0]['geometry']['location']['lng'];
print $coords;
echo "<br><br>";
?>

Reply all
Reply to author
Forward
0 new messages