I'm trying to get json response from google maps using this code:
var address = 'Sydney,NSW';
$.ajax({
type: "GET",
url: "http://maps.googleapis.com/maps/api/geocode/json?sensor=false",
dataType: "jsonp",
data: ({"address":address}),
success: function(json){
if (json.status == "OK") {
alert(":)");
} else {
alert('wrong!');
}
}
});
It's working really good, but...
as a result i'm getting
Uncaught SyntaxError: Unexpected token :
in Chrome and
Error: no element found in FireFox..
it's seems that something wrong is with returned JSON, but it looking good:
{
"status": "OK",
"results": [ {
"types": [ "locality", "political" ],
"formatted_address": "Sydney New South Wales, Australia",
"address_components": [ {
"long_name": "Sydney",
"short_name": "Sydney",
"types": [ "locality", "political" ]
}, {
"long_name": "New South Wales",
"short_name": "New South Wales",
"types": [ "administrative_area_level_1", "political" ]
}, {
"long_name": "Australia",
"short_name": "AU",
"types": [ "country", "political" ]
} ],
"geometry": {
"location": {
"lat": -33.8689009,
"lng": 151.2070914
},
"location_type": "APPROXIMATE",
"viewport": {
"southwest": {
"lat": -34.1648540,
"lng": 150.6948538
},
"northeast": {
"lat": -33.5719182,
"lng": 151.7193290
}
},
"bounds": {
"southwest": {
"lat": -34.1692489,
"lng": 150.5022290
},
"northeast": {
"lat": -33.4245980,
"lng": 151.3426361
}
}
}
} ]
}
The return must be jsonp not json (the json should be wrapped into a function call)
Try using GM2 (looks like jsonp is not supported in GM3)
$.ajax({
type: "GET",
url: "http://maps.google.com/maps/geo?sensor=false&output=json&"+$.param({"q":address}),
dataType: "jsonp",
success: function(json){
if (json.Status.code == "200") {
alert(":)");
} else {
alert('wrong!');
}
}
});
Related
I'm looping over my data that's returned from a Google API to receive the city and state, but I keep receiving this error
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Geocode'.
No index signature with a parameter of type 'string' was found on type 'Geocode'.
Which appears when I try to loop the data:
data[key].address_components.forEach
So far I looked at "Indexing objects" and using a interface, but I'm still not sure how to use them
Here is my code so far:
type Geocode = {
data?: google.maps.GeocoderResult | null;
error: string | null;
};
export interface CityState {
city?: string;
state?: string;
}
export const parseForCityAndState = (data: Geocode): CityState => {
const cityState = {
city: '',
state: '',
};
if (data) {
for (const key in data) {
data[key].address_components.forEach((ele: {types: string | string[]; short_name: string}) => {
if (ele.types.includes('sublocality') || ele.types.includes('locality')) {
cityState.city = ele.short_name;
}
if (ele.types.includes('administrative_area_level_1')) {
cityState.state = ele.short_name;
}
});
}
}
return cityState;
};
Here is how the google JSON returns the data:
{
"data": {
"address_components": [
{
"long_name": "254",
"short_name": "254",
"types": [
"street_number"
]
},
{
"long_name": "Broadway",
"short_name": "Broadway",
"types": [
"route"
]
},
{
"long_name": "Manhattan",
"short_name": "Manhattan",
"types": [
"political",
"sublocality",
"sublocality_level_1"
]
},
{
"long_name": "New York",
"short_name": "New York",
"types": [
"locality",
"political"
]
},
{
"long_name": "New York County",
"short_name": "New York County",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "New York",
"short_name": "NY",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "United States",
"short_name": "US",
"types": [
"country",
"political"
]
},
{
"long_name": "10007",
"short_name": "10007",
"types": [
"postal_code"
]
}
],
"formatted_address": "254 Broadway, New York, NY 10007, USA",
"geometry": {
"location": {
"lat": 40.7129032,
"lng": -74.0063033
},
"location_type": "ROOFTOP",
"viewport": {
"south": 40.7115542197085,
"west": -74.0076522802915,
"north": 40.7142521802915,
"east": -74.00495431970849
}
},
"place_id": "ChIJzwO0CyJawokRoSRPRCTv9II",
"plus_code": {
"compound_code": "PX7V+5F New York, NY, USA",
"global_code": "87G7PX7V+5F"
},
"types": [
"street_address"
]
},
"error": null
}
This is a problem caused by the fact that TSC does not know whether that object can be indexed by a string. This is normally solved by typing whatever you're indexing as Record<string, T>.
const data: Record<string, any> = ...;
data[key].address_components.forEach
You can also cast it:
(data as Record<string, any>)[key]
I have a string that looks like the following:
{
"results": [
{
"address_components": [
{
"long_name": "Ireland",
"short_name": "Ireland",
"types": [
"establishment",
"natural_feature"
]
}
],
"formatted_address": "Ireland",
"geometry": {
"bounds": {
"northeast": {
"lat": 55.38294149999999,
"lng": -5.431909999999999
},
"southwest": {
"lat": 51.4475448,
"lng": -10.4800237
}
}],
"status" : "OK"
}
I want to turn this into a json that I can easily traverse. However when I call JSON.parse() on this string I get a json array that is a pain to traverse. I want to be able to extract the lat and lng from northeast without having to loop through the entire array.
var json = `{
"results": [
{
"address_components": [
{
"long_name": "Ireland",
"short_name": "Ireland",
"types": [
"establishment",
"natural_feature"
]
}
],
"formatted_address": "Ireland",
"geometry": {
"bounds": {
"northeast": {
"lat": 55.38294149999999,
"lng": -5.431909999999999
},
"southwest": {
"lat": 51.4475448,
"lng": -10.4800237
}
}
}
}
],
"status" : "OK"
}`;
var data = JSON.parse(json);
var bounds = data.results[0].geometry.bounds;
var bound = bounds.northeast || bounds.southwest;
console.log(bound.lat, bound.lng);
If you know northeast is always an option you can simplify this to:
console.log(data.results[0].geometry.bounds.northeast);
That will give you your lat and lng.
I am trying to query the following data:
(obtained from:https://dotnetcodr.com/2017/06/21/introduction-to-couchdb-with-net-part-17-starting-with-mango-queries/)
{
"post_code": 35801,
"country": "United States",
"country_abbreviation": "US",
"places": [
{
"place_name": "Huntsville",
"longitude": -86.5673,
"state": "Alabama",
"state_abbreviation": "AL",
"latitude": 34.7269
}
]
},
..........
My question:
How to include, say, firstly, the place_name, in the query.
The following javascript does not give a result:
{
"selector": {
"post_code": {"$eq": 35801}
},
"fields":["places.placename"]
}
correct index on post_code:
{
"index": {
"fields": [
"post_code"
]
},
"type": "json",
"name": "post-code-index"
}
I did set up an additional index as follows:
{
"index": {
"fields": [
"places.placename"
]
},
"type": "json"
}
What if the data had the following field:
"old_post_code_numbers": [12345, 67890, ......]
or:
What if the data had the following fields:
"places":
{
"place_name": "Huntsville",
"longitude": -86.5673,
"state": "Alabama",
"state_abbreviation": "AL",
"latitude": 34.7269
}
JSON has so many forms and I struggle to get a handle on the principles behind the javascript required for these kind of queries.
I know it is simple. It must be simple.
Many thanks for any guidance or websites I should/could visit.
Edit:
I managed to get the following to work on an online javascript testing site, but I still could not get this to work in CouchDB Mango. Surely this is possible in CouchDB.???
var xxx=
{
"post_code": 82941,
"country": "United States",
"country_abbreviation": "US",
"places": [
{
"place_name": "Pinedale",
"longitude": -109.8561,
"state": "Wyoming",
"state_abbreviation": "WY",
"latitude": 42.8543
}]
}
console.log(xxx.places[0].place_name);
I have been able to get a result for part 1. of my question (based on the answer to this question), as follows:
My index:
{
"type": "json",
"def": {
"fields": [
{
"places.0.place_name": "asc"
}
]
}
}
My query:
{
"selector": {
"places.0.place_name": {
"$gte": null
}
},
"fields": [
"_id",
"places.0.place_name"
],
"sort": [
{
"places.0.place_name": "asc"
}
]
}
Result:
{"docs":[
{"_id":"254b9a8c7a46934363076cc3d9034082","places":{"0":{"place_name":"Aberdeen"}}},
{"_id":"254b9a8c7a46934363076cc3d9037559","places":{"0":{"place_name":"Altavista"}}},
{"_id":"254b9a8c7a46934363076cc3d900e4d2","places":{"0":{"place_name":"Anchorage"}}},
{"_id":"254b9a8c7a46934363076cc3d900f3b9","places":{"0":{"place_name":"Anchorage"}}},
{"_id":"254b9a8c7a46934363076cc3d902c738","places":{"0":{"place_name":"Ashland"}}},
{"_id":"254b9a8c7a46934363076cc3d901a2f2","places":{"0":{"place_name":"Atlanta"}}},
{"_id":"254b9a8c7a46934363076cc3d901a374","places":{"0":{"place_name":"Atlanta"}}}
.................
In this case I have omitted the "post_code": {"$eq": 35801} but this can be added without an error occurring.
part3:
Index:
{
"index": {
"fields": [
{
"places.place_name": "asc"
}
]
},
"type": "json"
}
Query:
{
"selector": {
"places.place_name": {
"$gte": null
}
},
"fields": [
"places.place_name"
],
"sort": [
{
"places.place_name": "asc"
}
]
}
Result:
{"docs":[
{"places":{"place_name":"Anchorage"}},
{"places":{"place_name":"Anchorage"}},
{"places":{"place_name":"Huntsville"}},
{"places":{"place_name":"Huntsville"}},
{"places":{"place_name":"Phoenix"}},
{"places":{"place_name":"Phoenix"}}
]}
Part 2:
Index:
{
"index": {
"fields": [
{
"old_post_code_numbers": "asc"
}
]
},
"type": "json"
}
Query:
{
"selector": {
"old_post_code_numbers": {
"$gte": null
}
},
"fields": [
"places.place_name",
"old_post_code_numbers"
],
"sort": [
{
"old_post_code_numbers": "asc"
}
]
}
Result:
{"docs":[
{"places":{"place_name":"Huntsville"},"old_post_code_numbers":[12345,67890]},
{"places":{"place_name":"Huntsville"},"old_post_code_numbers":[12345,67890]},
{"places":{"place_name":"Anchorage"},"old_post_code_numbers":[12345,67890]},
{"places":{"place_name":"Anchorage"},"old_post_code_numbers":[12345,67890]},
{"places":{"place_name":"Phoenix"},"old_post_code_numbers":[12345,67890]},
{"places":{"place_name":"Phoenix"},"old_post_code_numbers":[12345,67890]}
]}
The last example using: "old_post_code_numbers.0" throughout, gives:
{"docs":[
{"places":{"place_name":"Huntsville"},"old_post_code_numbers":{"0":12345}},
{"places":{"place_name":"Huntsville"},"old_post_code_numbers":{"0":12345}},
{"places":{"place_name":"Anchorage"},"old_post_code_numbers":{"0":12345}},
{"places":{"place_name":"Anchorage"},"old_post_code_numbers":{"0":12345}},
{"places":{"place_name":"Phoenix"},"old_post_code_numbers":{"0":12345}},
{"places":{"place_name":"Phoenix"},"old_post_code_numbers":{"0":12345}}
]}
I would appreciate any comments.
I'm trying to use GraphHopper Route Optimization API for solving VRP with pickups and deliveries. I want to test it with an example from https://graphhopper.com/dashboard/#/editor. My request goes like this:
var vrp = {
"vehicles": [
{
"vehicle_id": "my_vehicle",
"start_address": {
"location_id": "berlin",
"lon": 13.406,
"lat": 52.537
}
}
],
"services": [
{
"id": "hamburg",
"name": "visit_hamburg",
"address": {
"location_id": "hamburg",
"lon": 9.999,
"lat": 53.552
}
},
{
"id": "munich",
"name": "visit_munich",
"address": {
"location_id": "munich",
"lon": 11.57,
"lat": 48.145
}
},
{
"id": "cologne",
"name": "visit_cologne",
"address": {
"location_id": "cologne",
"lon": 6.957,
"lat": 50.936
}
},
{
"id": "frankfurt",
"name": "visit_frankfurt",
"address": {
"location_id": "frankfurt",
"lon": 8.67,
"lat": 50.109
}
}
]
};
$.ajax({
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
type: "POST",
url: 'https://graphhopper.com/api/1/vrp/optimize?key=[...]',
data: vrp,
dataType: "json",
success: function(json){
console.log(json);
}});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I get the following response:
screenshot
Waht may be the problem here?
I'have found solution in another so-question Send JSON data with jQuery.
Just use data: JSON.stringify(vrp)
I'm parsing JSON response from the MapQuest API. I need all of the 'narratives' from the 'legs' node under 'maneuvers' (legs-> maneuvers -> get all narratives), but I cannot figure it out.
I can get most of the values like so:
$(function(){
var mq = jQuery.parseJSON(jsonResponse);
$("#fuel").html(mq.renderMatrixResults[0].route.fuelUsed);
$("#rtime").html(mq.renderMatrixResults[0].route.realTime);
});
Part of JSON response:
{
"renderMatrixResults": [
{
"route": {
"hasTollRoad": true,
"computedWaypoints": [
],
"fuelUsed": 2.24,
"hasUnpaved": false,
"hasHighway": true,
"realTime": 5556,
"boundingBox": {
"ul": {
"lng": -74.240074,
"lat": 40.662548
},
"lr": {
"lng": -74.132072,
"lat": 40.573451
}
},
"distance": 38.998,
"time": 5523,
"hasSeasonalClosure": false,
"locations": [
{
"latLng": {
"lng": -74.18862,
"lat": 40.609712
},
"adminArea4": "Brooklyn",
"adminArea5Type": "City",
"adminArea4Type": "County",
"adminArea5": "Brooklyn",
"street": "1234 Test Lane",
"adminArea1": "US",
"adminArea3": "NY",
"type": "s",
"displayLatLng": {
"lng": -74.188621,
"lat": 40.60971
},
"linkId": 33589148,
"postalCode": "10001-6992",
"sideOfStreet": "L",
"dragPoint": false,
"adminArea1Type": "Country",
"geocodeQuality": "POINT",
"geocodeQualityCode": "P1AAA",
"adminArea3Type": "State"
},
{
"latLng": {
"lng": -74.194858,
"lat": 40.601623
},
"adminArea4": "Brooklyn",
"adminArea5Type": "City",
"adminArea4Type": "County",
"adminArea5": "Brooklyn",
"street": "5678 Example Street",
"adminArea1": "US",
"adminArea3": "NY",
"type": "s",
"displayLatLng": {
"lng": -74.194854,
"lat": 40.601623
},
"linkId": 33361764,
"postalCode": "10001-5483",
"sideOfStreet": "R",
"dragPoint": false,
"adminArea1Type": "Country",
"geocodeQuality": "POINT",
"geocodeQualityCode": "P1AAA",
"adminArea3Type": "State"
}
],
"hasCountryCross": false,
"legs": [
{
"hasTollRoad": false,
"index": 0,
"roadGradeStrategy": [
[
]
],
"hasHighway": false,
"hasUnpaved": false,
"distance": 0.882,
"time": 145,
"origIndex": 1,
"hasSeasonalClosure": false,
"origNarrative": "Go west on some road",
"hasCountryCross": false,
"formattedTime": "00:02:25",
"destNarrative": "Proceed to 789 GIRAFFE STREET",
"destIndex": 1,
"maneuvers": [
{
"signs": [
],
"index": 0,
"maneuverNotes": [
],
"direction": 4,
"narrative": "Start out going south on Elephant Avenue.",
"iconUrl": "https://content.mapquest.com/mqsite/turnsigns/icon-dirs-start_sm.gif",
"distance": 0.57,
"time": 79,
"linkIds": [
],
"streets": [
"Elephant Avenue"
],
"attributes": 0,
"transportMode": "AUTO",
"formattedTime": "00:01:19",
"directionName": "South",
"mapUrl": "https://www.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luur20uanq,b0=o5-9ayxdw&type=map&size=225,160&pois=purple-1,40.60971,-74.188621,0,0|purple-2,40.602351999999996,-74.189582,0,0|�er=40.606031,-74.18910149999999&zoom=10&rand=-1416511403&session=53c1fb45-030d-0004-02b7-16b5-00163e4c0d3f",
"startPoint": {
"lng": -74.188621,
"lat": 40.60971
},
"turnType": 2
},
{
"signs": [
],
"index": 1,
"maneuverNotes": [
],
"direction": 7,
"narrative": "Turn right onto Tiger Blvd.",
"iconUrl": "https://content.mapquest.com/mqsite/turnsigns/rs_right_sm.gif",
"distance": 0.269,
"time": 56,
"linkIds": [
],
"streets": [
"Tiger Blvd"
],
"attributes": 0,
"transportMode": "AUTO",
"formattedTime": "00:00:56",
"directionName": "West",
"mapUrl": "https://www.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luur20uanq,b0=o5-9ayxdw&type=map&size=225,160&pois=purple-2,40.602351999999996,-74.189582,0,0|purple-3,40.601127,-74.194366,0,0|�er=40.601739499999994,-74.191974&zoom=12&rand=-1416511403&session=53c1fb45-030d-0004-02b7-16b5-00163e4c0d3f",
"startPoint": {
"lng": -74.189582,
"lat": 40.602352
},
"turnType": 2
}
Haven't tested it but here is the idea. You can use a function that will traverse object tree and collect items specified by a path.
function getPath(path, obj) {
var name, value;
path = path instanceof Array ? path: path.split('.'); //convert path to array
name = path.shift(); //get the first name
value = obj[name]; //extract value
if(!path.length || value == null) { //last name or value is null or undefined
return value;
}
if(value instanceof Array) { //if value is array - concat
return [].concat.apply([], value.map(function(item){
return getPath(path.slice(0), item);
}));
}
return getPath(path, value); //else go deeper
}
Usage:
var narratives
= getPath('renderMatrixResults.route.legs.maneuvers.narrative', mq);
I believe the path is correct.