Can't get longitude and latitude from array - javascript

I am trying to store the latitude and the longitude from an array where its length is sometimes 1 ,sometimes 2 or 3 .
Here is the code:
var latitude,longitude;
$.each(data.results, function (i, item) {
var name = item.from_user;
var img = item.profile_image_url;
var text=item.text;
var profile_img=item.profile_image_url;
var url=(item.entities.urls.length > 0 ? item.entities.urls[0].url : '');
Placemaker.getPlaces(text,function(o){
console.log(o);
if (typeof(o.match!=='undefined') ||(o.length==1)){
latitude=o.match.place.centroid.latitude, longitude=o.match.place.centroid.longitude;
console.log(latitude,longitude);}
else if (typeof(o.match[0]!=='undefined') ||(o.match.length==2)){
latitude=o.match[0].place.centroid.latitude, longitude=o.match[0].place.centroid.longitude;
console.log(latitude,longitude);
}
});
array.push({name:name,img:img,text:text,latitude:latitude,longitude:longitude,profile_img:profile_img,url:url});
From this code I get only the latitude & longitude values when the array length is 1. So only the first if is executed. I am trying to fix the others so that I can get values from the other arrays as well, since when I use console.log to output the array, the values of latitude & longitude are not there. I guess that the loop has to finish getting all the values before putting them into the array.
I am trying to output the tweets on the google map via the tweets location. I am not using geocode but yahoo placemaker to geolocate the location from the text of the tweet.
here is a snapshot of the placemaker array structure http://www.flickr.com/photos/codepo8/3553188917/
this is the other array that am trying to get values Object { match=[2]}

typeof(o.match!=='undefined') is always "boolean"
I think you want
typeof(o.match)!=='undefined' or just typeof o.match!=='undefined'

Related

Create 2D Array out of another Array which is casted against an API

I'm working on a project using the opengeodata and some company-internal APIs. Therefore the code I'm using here is slightly changed.
First I'm using the Opencagedata Javascript API to get the lat/lng-Coordinates out of an address.
<script>
function geocode(query) {
$.ajax({
url: 'https://api.opencagedata.com/geocode/v1/json',
method: 'GET',
data: {
'key': 'MyKey',
'q': query,
'no_annotations': 1
},
dataType: 'json',
statusCode: {
200: function(response){ // success
var lat = response.results[0]['geometry']['lat'];
var lng = response.results[0]['geometry']['lng'];
$('#geo_result').text(lat + ' , ' + lng);
After that I'm using another internal API to get some information about places surrounding this location. Lets call them POI.
After getting those POIs I'm using splice to filter the three nearest POIs to the lat/lng Coordinates and filter on some specific keywords.
var radius = 1.5;
var POI = [];
var apiCall = $.get("CoorpAPI/" + radius + "/around/" + lat + "," + lng);
apiCall.done(function(result) {
var myLoc = result.filter(function(loc) {
return loc.id.substr(0, 3) != 'keyword';
});
$.each(myLoc, function(n, loc) {
POI.push(loc.id)
})
var top3 = POI.slice(0,3);
console.log(top3);
Now I want to run those three "top3" POIs ["AB1234", "BC2345", "CD3456"] against a second API which is returns location information.
Those information are supposed to be written into the same array into the second second dimension.
In the end I want to have something Like:
[
0: AB1234
Location Information: A
Location Information: B
1: CD2345
Location Information: C
Location Information: D
...
]
I guess the loop would have to look somewhat like this, but I'm not sure how to call the API and create a 2d-array out of the "top3" locations and the location information returned by the api:
for (var i = 0; i < top3.length; i++) {
var apiCall_2 = $.get("CoorpAPI_2"+top3[i]);
// ???
}
If I understand you correctly, you want to use a nested array inside POI to add more information after a second API call. One thing you can try is to push an array instead of just loc.id in the following manner:
POI.push([loc.id]);
Now you have a nested array in POI instead of a single string ID (I am guessing the ID is string; can be a number as well). For the second API call you can modify your code like this:
var apiCall_2 = $.get('CoorpAPI_2'+top3[i][0]);
In this way, you are using the ID which, is the first element in the nested array. Once you process all your data from API call 2, you can either push each data point separately into the nested array or, as another array like this:
// pushing each data points separately
top3[i].push(dataPoint1);
// ... up to say N data points
top3[i].push(dataPointN);
// adding as an array
top3[i].push([dataPoint1, dataPoint2, dataPointN]);
Your result will be like this:
[ ["AB1234", "dataPoint1", "dataPoint2"] ]
if you use the first approach and like this
[ [ "AB1234", ["dataPoint1", "dataPointN"] ], ]
if you use the second approach. Hope this helps.

how to convert json array result object as non array values

I have a json result of latitude longiude as an array result like this, [13.0801721, 80.2838331] .
I want to convert this just as comma seprated valueswithout array brackets lik this, 13.0801721, 80.2838331. Please help
Here is my problem.
i want to get this array of
var myLatlng = new google.maps.LatLng([13.0801721, 80.2838331]); json result like this
var myLatlng = new google.maps.LatLng(13.0801721, 80.2838331);
please see screenshot
enter image description here
You can call your function like this:
let result=[13.0801721, 80.2838331];
let myLatlng = new google.maps.LatLng(...result);
This uses the Spread Syntax

How to calculate two values from bracket in javascript

I am creating geofencing featured website. So I need to calculate some expression. I have two values related to latitude and longitude.
for e.g: var value = '(41.878113,-87.629798)'
How to separate above two values in javascript
The Google Maps LatLng API provides .lat() and .lng() functions for accessing them individually. You can use them like this:
var coords = new google.maps.LatLng(42.878113,-87.629798);
console.log(coords.lat()); // 42.878113
console.log(coords.lng()); // -87.629798
That's not valid JavaScript. (Post was edited, it wasn't valid at first)
One method you could do is define it as an array:
var cords = [41.878113, -87.629798];
From here you could reference it like so:
cords[0]; // Out: 41.878113
cords[1]; // Out: -87.629798
An easy way would be to separate the string at the , then remove non-numeric characters
var value = '(41.878113,-87.629798)';
var parts = value.split(',');
//=> ["(41.878113", "-87.629798)"]
var lat = parts[0].replace(/[^\d.-]/g, '');
//=> "41.878113"
var lng = parts[1].replace(/[^\d.-]/g, '');
//=> "-87.629798"
Now you can use them in some sort of calculation
calculateSomething(lat, lng);
Which would be the same as
calculateSomething("41.878113", "-87.629798");
If value is a String that is always in that format and you want an Array that contains the 2 values in String format , this example should suffice
var value = '(41.878113,-87.629798)';
document.getElementById('out').textContent = JSON.stringify(value.slice(1, -1).split(','), null, 2);
<pre id="out"></pre>

Remove Duplicate Items From Multidimensional Array Using Javascript, jQuery, & underscore.js

I have a web page which uses jQuery to fetch data from a JSON file that contains a location name, latitude, and longitude. I then push the retrieved data into an array.
var weatherSites = [];
function weather() {
$.getJSON('json/LOCS.json', function(data) {
$.each(data.locations, function() {
var locationLatitude = this.latitude;
var locationLongitude = this.longitude;
var locationName = this.location;
// -- If the latitude and longitude are 0,0 then skip to the next iteration --
if (locationtLatitude == +0 || locationLatitude == -0 && locationLongitude == +0 || locationLongitude == -0) {
return true;
}
// Populate array with site name, latitude, and longitude
weatherSites.push({name: locationName, latitude: locationLatitude, longitude: locationLongitude});
});
});
};
The code retrieves the data and populates the array as required. However, there are a number of locationName items which are the same, even though the locationLatitude and/or locationLongitude are different. I need to remove from the array elements where the locationNames are the same, regardless of the latitude or longitude.
I have tried using a number of methods seen here but have had no luck. For example:
function removeDupes() {
var uniques = _.map(_.groupBy(weatherSites,function(doc){
return doc.id;
}),function(grouped){
return grouped[0];
});
This example requires underscore.js. This did not work for me. I am new to programming and GIS in general. I would appreciate an answer which contains the full code necessary and hopefully the logic behind what is happening. This would be very helpful for me and will of course help me to learn.
Thank you for your help.
The open source project http://www.jinqJs.com can easily do it.
Here is the GitHub link: GitHub
var results = jinqJs()
.from(data1)
.groupBy('locationName')
.max('locationLatitude', 'locationLongitude')
.select();
Let me know if you need any working examples.

Beginner fusion table query...two column location and st_distance

I'm altering a google example template to try to construct a query that finds the nearest location in the table to the user-entered city. And in this example, I just want to output the lat and lon and probably the "id" of the nearest table location to the user-inputted city. First, I'm using my LATITUDE column as location because it's been geocoded in the table as a two-column location. Strangely, when I alerted that variable, it only displays the latitude instead of the lat/lng coordinates. I thought since LATITUDE was acting as a two column location, it would return a lat/lng.
So when I run this simple query after pushing the "go" button after entering a city:
var queryList = [];
queryList.push("SELECT LATITUDE,LONGITUDE FROM ");
queryList.push(tableid);
and then alert the values, in the popup window, it works fine: http://greenandtheblue.com/whentoplant/test_query_geocode.html, alerting a lat and lon from the table...what I hoped it would.
But when I try to use the st_distance, I don't get any suggestion that it's working.
queryList.push("ORDER BY ST_DISTANCE(LATITUDE, LATLNG("+coordinate.lat()+","+coordinate.lng()+")) LIMIT 1");
http://greenandtheblue.com/whentoplant/test_query_geocode_notworking.html
I prefer this method of querying...seems simpler:
query: {
select: 'LATITUDE',
from: tableid
},
but I gathered from the example that I needed to put the second query (acted on when I push go) in an array of sorts, which makes it a bit more complicated.
I hope this is a clear enough question. Thanks for any help.
Shad
If I make the query like this:
queryList.push("SELECT STATION,STATION_NAME,ELEVATION,LATITUDE FROM ");
queryList.push(tableid);
//query seems to work when I comment out the line below.
queryList.push("ORDER BY ST_DISTANCE(LATITUDE, LATLNG("+coordinate.lat()+","+coordinate.lng()+")) LIMIT 1");
var query = encodeURIComponent(queryList.join(' '));
var gvizQuery = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tq=' + query);
gvizQuery.send(function(response) {
var datatable = response.getDataTable();
var header = 'No results';
var content = 'Sorry, no store delivers here.';
if (datatable && (datatable.getNumberOfRows() > 0)) {
header = datatable.getValue(0, 0);
content = datatable.getValue(0, 1)+"<br>Station:"+datatable.getValue(0,0)+"<br>Elevation:"+datatable.getValue(0,2);
}
infoWindow.setContent('<h3>' + header + '</h3>' +
'<p>' + content + '</p>');
infoWindow.setPosition(coordinate);
infoWindow.open(map);
});
It works for me.
changed:
var query = encodeURIComponent(queryList.join('')); // empty string
to:
var query = encodeURIComponent(queryList.join(' ')); // single space

Categories

Resources