Get coordinates of a place using Wikidata - javascript

I am using Wikidata API to get birth location from famous people, and then displaying the location using Google Maps API. Here is the Wikidata request I use :
SELECT DISTINCT ?item ?itemLabel ?birthLocation ?birthLocationLabel WHERE {
?item (wdt:P31|wdt:P101|wdt:P106)/wdt:P279* wd:Q482980 ;
rdfs:label "Mary Wollstonecraft"#en ;
wdt:P19 ?birthLocation
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
I'm then using a google geocoder to get a lat lng from the birthLocationLabel, and displaying it on the map, however sometimes the geocoder can't find a location (maybe the place doesn't exist anymore), so I'd like to know if it was possible to get coordinates from the wikidata query ? I know birth location has a "coordinate location" property, but I don't know how to access it.
Here is the link of the wikidata query

This works for me ?birthLocation wdt:P625 ?coordinates so the whole query would be:
SELECT DISTINCT ?item ?itemLabel ?coordinates ?birthLocation ?birthLocationLabel
WHERE {
?item ((wdt:P31|wdt:P101|wdt:P106)/(wdt:P279*)) wd:Q482980;
rdfs:label "Mary Wollstonecraft"#en;
wdt:P19 ?birthLocation.
?birthLocation wdt:P625 ?coordinates.
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
This returns:
[{
"item": "http://www.wikidata.org/entity/Q101638",
"itemLabel": "Mary Wollstonecraft",
"coordinates": "Point(-0.075 51.5166)",
"birthLocation": "http://www.wikidata.org/entity/Q123219",
"birthLocationLabel": "Spitalfields"
}]

Related

Javascript Querying on Elasticsearch does not work on Child Elements

I am trying to display searchresults on a elasticsearch database in my reactjs-app. Nevertheless I can only access the upper layer of key value pairs and am unable to reach the children.
The structure of my elasticsearch-objects is as follows:
...
"hits":[{
"_index":"knowledgecrawler",
"_type":"doc",
"_id":"5fea73f38399f4c01f",
"_score":1.0,
"_source":{
"content":"content comes here",
"meta":{
"author":"Jones#stackoverflow.com",
"title":"I am lost"
"date":"today",
"keywords":["Stackoverflow"],
"language":"Javascript",
}
"raw":{
"date":"2017-03-08",
"subject":"How do I get here?"
}
}}]
The elasticsearch-object is much bigger, but I am only searching in the "hits". With the following lines of code i can easily display the firstlevel values(_index, _type, _id), but any attempt to access the children failed so far:
render() {
const result = this.props.result;
return (
<div className={this.props.bemBlocks.item().mix(this.props.bemBlocks.container("item"))} key={result._id}>
<div className={this.props.bemBlocks.item("title")}>{result._id}</div>
<div className={this.props.bemBlocks.item("title")}>{result._type}</div>
</div>
)
}
Can anybody advice me how to access the children of _source. E.g. I want to display the author in my frontend.
EDIT:
So the error is apparently due to the fact that the _source field in Elasticsearch is not indexed and thus not searchable (according to the elasticsearch docs). I haven't come up with a solution so far, but will post it here, when I find it. Help is also much appreciated.
Let's say you have following data:
data = {"hits":[{
"_index":"knowledgecrawler",
"_type":"doc",
"_id":"5fea73f38399f4c01f",
"_score":1.0,
"_source":{
"content":"content comes here",
"meta":{
"author":"Jones#stackoverflow.com",
"title":"I am lost"
"date":"today",
"keywords":["Stackoverflow"],
"language":"Javascript",
}
"raw":{
"date":"2017-03-08",
"subject":"How do I get here?"
}
}}]}
Now you question is : Can anybody advice me how to access the children of _source. E.g. I want to display the author in my frontend.
So, you can do the following to get the author of _source:
{data.hits && data.hits.length > 0 && data.hits[0]._source && data.hits[0]._source.meta && data.hits[0]._source.meta.author ?data.hits[0]._source.meta.author : ''}
If you have multiple hits, then you can use array.map() like this:
data.hits.map(value => value._source && value._source.meta && value._source.meta.author ? value._source.meta.author : '')

How to get postcode of a county through google api

I am trying to create an autocomplete text field which should only provide the postal code in dropdown. Here is the documentation which I have followed:
google place autocomplete
How do i get only and all the postcodes of UK over there.
src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"
src="https://maps.googleapis.com/maps/api/js?key=your_api_key&libraries=places&sensor=false&callback=initialize"
function initialize() {
$('#adv_postcode').each(function () {
initialize2(this);
});
}
function initialize2(elementID) {
var options = {
componentRestrictions: {
country: 'uk'
}
};
var autocomplete_element = new google.maps.places.Autocomplete(elementID, options);
autocomplete_element.addListener('place_changed', function () {
elementID.value = fillInAddress(autocomplete_element);
});
}
<input type="text" name="adv_postcode" id="adv_postcode" class="addressfields"/>
Any help highly appreciated
At the moment the best option that you have is setting types parameter of autocomplete options to (regions). According to the documentation
The (regions) type collection instructs the Places service to return any result matching the following types:
locality
sublocality
postal_code
country
administrative_area_level_1
administrative_area_level_2
source: https://developers.google.com/places/supported_types#table3
Not ideal, but you will get only regions in the list of suggestions. So your code should be
var options = {
componentRestrictions: {
country: 'uk'
},
types: ['(regions)']
};
var autocomplete_element = new google.maps.places.Autocomplete(elementID, options);
autocomplete_element.addListener('place_changed', function () {
elementID.value = fillInAddress(autocomplete_element);
});
Also, note that there is a feature request in Google issue tracker to make types parameter more flexible:
https://issuetracker.google.com/issues/35820774
Feel free to star this feature request to express your interest and subscribe to notifications.

Getting Currency Information From Country Code in PHP

I want to get the currency code information (for example:USD etc.) from country code.I tried most of methods but I cannot have this data.I had the country code from geolocation.
How can I solve this problem and get the currency code?
Copy the object in this page into your code, like this
var countryCurrencies = {
"BD": "BDT",
"BE": "EUR",
"BF": "XOF",
...
"UA": "UAH",
"QA": "QAR",
"MZ": "MZN"
}
//get your country code
var countryCode = "ma"; //For example
var currency = countryCurrencies.hasOwnProperty(countryCode.toUpperCase()) ? countryCurrencies[countryCode.toUpperCase()] : "Unkonw";
//The result : curreny = "MAD"
You can do with this following api its very easy and good
https://restcountries.eu/rest/v1/alpha/in
"in" be the country code for india.
Eg with jquery
jQuery.getJSON(
"https://restcountries.eu/rest/v1/alpha/in,
function (data) {
console.log(data.currencies)
}
);
in data: you get almost every information related to country
Here an Array with all Country Information:
<?php $location = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR'])); print_r($location) ?>

Making Rest call within a rest call angularjs

I am trying to make a REST call to get the total count of the cities based on the text entered in a textbox.
I am making the same REST call the second time to get 25 records for the same search text.
For example if I entered the text Paris, the 1st rest call will take the maxPage size to 1000 and get me all the records.
And the second time, the maxPage is set to 25 to get the first 25 records.
The idea is to show the total number of records matching the search text and also show the 1st 25 records.
(for ex: 25/400)
The problem that I am facing is by the time I am done with entering the text, the 1st rest call is taking only a part of the text and the 2nd call is taking the whole text.
The count returned for the text is not matching the 2nd call's response.
For example: the 1st call is ending up with the text 'Par' and getting me 250 results where as the 2nd call is taking 'Paris'. I am ending up with 25/250 which is not correct.
May be this is because of some timing issue since the searchCities is called on ng-change. I cannot introduce a button on the screen so it has to be ng-change only.
Please help me resolve this.
Please have a look at the below code.
$scope.getCityCount = function(phrase){
var searchPhrase = phrase;
var dataObj = { term: searchPhrase, maxPage: 1000, pagefrom: 0 };
var srchdata = JSON.stringify( dataObj );
Cities.query( {}, srchdata, function(cityData) { //1st REST call
if (cityData.status == "success") {
$scope.cityCount= cityData.data.length; //total records
$scope.loadMoreCities(searchPhrase); //2nd call:to get 25 records
}
});
}
$scope.loadMoreCities = function(phrase){
var searchParam = { term: phrase, maxPage: 25, pagefrom: 0 };
Cities.query( {}, searchParam, function(dataObj) {
if (dataObj.status == "success") {
var citiesFound = dataObj.data;
}
});
}
$scope.searchCities = function( phrase ) {
if(phrase.length > 1){
$scope.getCityCount(phrase);
}
}
EDIT:
Though I am searching for Paris, I am getting final result for Pa. Please see the logs::
getSearchCount#1: {"searchTerm":"Paris","maxPage":10000,"pagefrom":0}is=====400
getSearchCount#2: {"searchTerm":"Paris","maxPage":25,"pagefrom":0}is===== 25
getSearchCount#1: {"searchTerm":"Pari","maxPage":10000,"pagefrom":0}is===== 105
getSearchCount#2: {"searchTerm":"Pari","maxPage":25,"pagefrom":0}is===== 25
getSearchCount#1: {"searchTerm":"Pa","maxPage":10000,"pagefrom":0}is===== 722
getSearchCount#2: {"searchTerm":"Pa","maxPage":25,"pagefrom":0}is===== 25
On the screen I get 25/722
HTML:
<input type="text" ng-model="phrase" ng-change="searchCities(phrase)">
This is a pretty bad idea. You should do server side paging instead. Have the API return the pager object along with the search results. For example, here is an API GET request:
/api/accounts?searchText=someText&pageSize=25&page=1
Here is the response:
{
"pager": {
"pageCount": 1,
"totalItemCount": 342,
"pageNumber": 1,
"pageSize": 25,
"hasPreviousPage": false,
"hasNextPage": true,
"isFirstPage": true,
"isLastPage": false,
"firstItemOnPage": 1,
"lastItemOnPage": 25
},
"results": [
{
"id": 15343,
"name": "Account Name",
},
// more accounts returned here...
{
"id": 2314,
"name": "Account Name 2",
}
],
"searchText": "someText"
}
When the client wants to load more, the request would change to this:
/api/accounts?searchText=someText&pageSize=25&page=2
..where you see we're trying to fetch the 2nd page.
How you implement server side paging is another question. Here is a rudimentary server side paging example to give you an idea.
Update:
If you absolutely can't change the api to deliver paging information, try using a debounce delay. You can read about it in the documentation but it will essentially trigger the ng-change update when the timer expires instead of on the keypress. Here is how you would implement it.
<input type="text" ng-model="phrase" ng-model-options='{ debounce: 1000 }' ng-change="searchCities(phrase)">

Change content of a div based on an array within an array

Pastebin of index.html: http://pastebin.com/kdKFqTxe
Just copy and paste that and run it (this works but with some broken img links & no css).
With regards to the pastebin, just click on a node, and then click the first broken image below the video. What should happen is a dialogue box should appear with links to articles (from tubeArray). All relevant code is pasted below.
I'm trying to dynamically change the contents of a div when I click an image. The image has it's respective id (the first index in the inner array) within the first inner array there's another array (index 3). I want to populate my div (id="articleLinks") with those links using JQuery when the image is clicked.
JavaScript & JQuery:
The tube array. *Note: the first index of each element in tubeArray is the ID & the news articles aren't linked to anything particular. Only interested in tubeArray[0] & tubeArray[4]
var tubeArray = [
['UQ', -27.495134, 153.013502, "http://www.youtube.com/embed/uZ2SWWDt8Wg",
[
["example.com", "Brisbane students protest university fee hikes"],
["example.com", "Angry protests over UQ student union election"],
]
],
['New York', 40.715520, -74.002036, "http://www.youtube.com/embed/JG0wmXyi-Mw",
[
["example.com" , "NY taxpayers’ risky Wall Street bet: Why the comptroller race matters"]
]
],
['To The Skies', 47.09399, 15.40548, "http://www.youtube.com/embed/tfEjTgUmeWw",
[
["example.com","Battle for Kobane intensifies as Islamic State uses car bombs, Syrian fighters execute captives"],
["example.com","Jihadists take heavy losses in battle for Syria's Kobane"]
]
],
['Fallujah', 33.101509, 44.047308, "http://www.youtube.com/embed/V2EOMzZsTrE",
[
["example.com","Video captures family cat saving California boy from dog attack"],
["example.com","Fines of £20,000 for dogs that chase the postman"]
]
]
];
A for loop which goes through each element in tubeArray then assigns id to the first index. Also an image that calls the function myFunctionId which takes the parameter this.id.
for (i = 0; i < tubeArray.length; i++) {
var id = tubeArray[i][0];
//other code
'<img src="img.png" onclick="myFunctionId(this.id);" id="' + id + '">' +
//other code
}
function myFunctionId (id) {
journal = id;
alert(journal) //just a test
//I want to search through tubeArray with the id and find the matching inner array.
//I then want to loop through the innerArray and append to my html a link using JQuery.
$('#articleLinks').append("<a href='"+innerArray[0]+"'>"+innerArray[1]+'</a>'); // use CSS to break lines
}
}
HTML:
<div id="articleLinks">
Example Link<br>
</div>
Any help would be greatly appreciated. I've tried to simplify & cut out as much as I can so it's readable.
try this...
function myFunctionId (id) {
console.log(tubeArray);
tubeArray.forEach(function(entry) {
if (entry[0]==id) {
entry[4].forEach(function(innerArray){
$('#articleLinks').append("<a href='"+innerArray[0]+"'>"+innerArray[1]+'</a>'); // use CSS to break lines
});
return;
}
});
}
it makes it look like this for me... you're gonna have to handle that encoding issue. with the apostrophe. there are a lot of ways to handle it...
so.... if it was me... which it's not. but if it was... i would use an associative array instead of a numerically indexed one because it's easier to read the code and understand what you're using and where and how and things and stuff.
tubeArray = {
'UQ' : { 'location': [-27.495134, 153.013502],
'youtube': "example.com/embed/uZ2SWWDt8Wg",
'articles': [["example.com/queensland/brisbane-students-protest-university-fee-hikes-20140521-zrk8o.html", "Brisbane students protest university fee hikes"],
["example.com/content/2012/s3578878.htm", "Angry protests over UQ student union election"], ]
},
'New York': { 'location': [0.715520, -74.002036],
'youtube': "example.com/embed/JG0wmXyi-Mw",
'articles': [["example.com/2014/10/19/ny-taxpayers-risky-wall-street-bet-why-the-comptroller-race-matters/" , "NY taxpayers’ risky Wall Street bet: Why the comptroller race matters"]],
},
}

Categories

Resources