Trouble finding certain places using Here Places autosuggest - javascript

I have implemented the Here Places API for autocomplete suggestions. However a lot of places aren't showing up unless you type in the address. For example if I search for "Depannage 2ade" or different variant of that name, I dont get any results. However if I type in the physical address, I can get a result.
I figured this was because there wasn't enough information on the place in the Here app however I went on mapcreator.here.com to add information on the place in hope of adding it but I found that by typing in the address, in the map creator the name is already there. So I was wondering if there was maybe a parameter missing from my request that were preventing some places to show or maybe something that I'm doing wrong.
$.ajax({
url: "https://places.cit.api.here.com/places/v1/autosuggest" +
"?app_id=KEY" +
"&app_code=KEY",
dataType: "json",
data: {
q: val,
at: companyGeo.replace(" ",""),
size: '5',
result_types: 'address,place',
addressFilter: 'countryCode=fra'
},
type: "GET",
});
Basically I used address and places as filter and I search within the country of France. I can only find the place by typing the address and not the name. This isn't the case for ALL places but for many it is, and I find that odd since in the mapcreator they do have a place name entered.

Make sure you are using the new Places base URL:
https://places.ls.hereapi.com which uses the latest authentication method (apiKey). So retry your query with this new API URL.
Note also that the cit environment is only for testing and should not be used in production.
https://developer.here.com/documentation/places/dev_guide/common/request-cit-environment-rest.html
https://developer.here.com/documentation/places/dev_guide/topics/request-constructing.html

Related

How do I make a query to Google Places API?

I'm trying to make a client-side jquery request on an HTML page (in my Spring project) to the Google Places API so I can determine the ratings of a particular business type within a radius of x,y. At the moment I'm trying to do it like so:
function getCafe(){
$(document).ready(function(){
$('.search_latitude').val(marker.getPosition().lat());
$('.search_longitude').val(marker.getPosition().lng());
// These are lat long values calculated by the user's searched location on a google map on the client side
var Lat = marker.getPosition().lat();
console.log(Lat);
var Long = marker.getPosition().lng();
console.log(Long);
var cafeRatings = [];
// Ive disclosed my API Key
var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=" + Lat + "," + Long + "&radius=500&type=restaurant&keyword=cruise&key=MY_API_KEY";
$.ajax({
type: "GET",
dataType: "xml",
url: url,
success: function(xml) {
$(xml).find('results').each(function(){
$(this).find("rating").each(function(){
var rating = $(this).text();
cafeRatings.push(rating);
});
});
//This is a simple debug to display the contents of the rating array to ensure the parse worked correctly
alert(cafeRatings.join("\n"));
}
});
});
}
However Michael Geary's answer to this question Google's Places API and JQuery request - Origin http://localhost is not allowed by Access-Control-Allow-Origin has lead me to believe I cannot use an Ajax jquery to access the API this way and I have to "use the Places Library from the Maps API V3. (As I) can't just hit a URL directly from JavaScript or jQuery code."
With that being said I've found the documentation to do this to be quite broad and resources online seem to be quite limited. Has anyone any experience on how to simply get the rating elements from the API stored into an array in JS so I can calculate the average and display it in a text box?
In case it's needed this how the XML formatted API looks
<PlaceSearchResponse>
<status>OK</status>
<result>
<name>Sydney Showboats</name>
<vicinity>32 The Promenade, Sydney</vicinity>
<type>travel_agency</type>
<type>restaurant</type>
<type>food</type>
<type>point_of_interest</type>
<type>establishment</type>
<geometry>
<location>
<lat>-33.8675570</lat>
<lng>151.2015270</lng>
</location>
<viewport>
<southwest>
<lat>-33.8689120</lat>
<lng>151.2001126</lng>
</southwest>
<northeast>
<lat>-33.8662141</lat>
<lng>151.2028105</lng>
</northeast>
</viewport>
</geometry>
<rating>3.8</rating> <------ This is the element im trying to ad to the array
<icon>
https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png
</icon>
<reference>
CmRSAAAALItuCtuLapozzsjq3dmKqj7NDik149XsgUwHD3ob5AWfHYlZtykuJbQa0cq0GMqX8dRgucTCmitnXgV-ekE3GfV7910rzHhx3ZuadVYNuWMzLDVZDCj2G1yiBw8r_hhgEhCPDXsniaZ2ZrkvYyXFfmQrGhSzdmkAEz4stXNx2qFe-GqAlldzgw
</reference>
<id>ce4ffe228ab7ad49bb050defe68b3d28cc879c4a</id>
<opening_hours>
<open_now>false</open_now>
</opening_hours>
<photo>
<photo_reference>
CmRaAAAAh4dP9hsZ_6515QNxouVnuYFYKemmf8BE01rcaOvkFlILQiwGNe_OAX0ikmobMmWZJvyjsFEsn7j1TFhauHSrek8nY5GsW24_6nwJsqEwHTUC10SL5gQITHhkdam50G1PEhCP-C7Of2mkjqJCTYFeYGWuGhQjVoWASHiGSp3WHm26Bh2sYOglZw
</photo_reference>
<width>2048</width>
<height>1152</height>
<html_attribution>
Sydney Showboats
</html_attribution>
</photo>
<place_id>ChIJjRuIiTiuEmsRCHhYnrWiSok</place_id>
<scope>GOOGLE</scope>
</result>
........
</PlaceSearchResponse>
My previous advice remains the same: you can't use the server-oriented web service version of the Places API. You have to use the JavaScript client library. It is much easier to use than the web service API (even if you were allowed to use that), because you don't have to parse any XML, just access the object properties that the client library provides.
There are several examples in the Places Library documentation. The Place Search example is fairly close to what you are doing. It looks like you want to access the rating for a place, and that is easy with the JavaScript library; simply use the rating property of your place object (or whatever name you give that variable).
I took the Place Search example and updated the fiddle to illustrate accessing the rating property. Try it out and see if it helps answer your question.
In any case, the bottom line is unchanged: you can't use the web service API, you need to use the JavaScript client library, but that is a Good Thing, as the client library does most of the work for you.
If the question is how to compute the average rating for the places you receive back from the API, that is simple: write a loop and do the arithmetic. If you look at the fiddle you will see where it has a loop that iterates over the results variable that the API callback receives. The loop in the fiddle creates a marker for each element of results, but you can do whatever you want there. Just add up all the rating values and divide the total by results.length and you have your average. Of course check that the length is nonzero, so you don't divide by zero.
For example, if you have a results variable with the array of places results, you could do:
var totalRating = 0;
results.forEach( function( place ) {
totalRating += place.rating;
});
var averageRating = results.length == 0 ? 0 : totalRating / results.length;

How to display a newly randomly generated quote from a specific API when clicking a button?

Problem- I have an API that displays a random quote once the page loads. My button(div) called "newQuote" doesn't generate a new quote, instead, it displays the exact same quote, making my button useless.
My code can be found on GitHub here
SO-
I have a javascript function, called getNewQuote() that runs when my page loads. This function grabs a quote and author from an API (https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1), and appends it to my div with the class quoteTitle and quoteDisplay.
function getNewQuote() {
$.ajax({
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
jsonp: 'jsonp',
cache: 'false',
success: function(data) {
var post = data.shift();
$("#quoteTitle").empty();
$("#quoteDisplay").empty();
$("#quoteTitle").append(post.title);
$("#quoteDisplay").append(post.content);
}
});
}
getNewQuote();
Then, I set another div called newQuote which, when clicked, would display a new quote.
$('#newQuote').on('click', function(e) {
e.preventDefault();
getNewQuote();
Now, to me, it seems that the problem is caching. The reason that I think it is a cache problem is because if I go to the site on my phone using the app Firefox Focus, which (pretty sure) doesn't store any cache, the site will run as wanted, and will change my quote whenever I click on my #newQuote. You can try it for yourself at 'rqg.ronlaniado.me', where it is hosted.
Since my problem is cache, I did use some methods and plans to avoid this.
cache: 'false',
I set cache-ing to false in my .ajax request.
<script src="qg_js.js?v=42"></script>
I put "?v-42 which, according to Google, shouldn't keep cache stored.
If anyone can look through my code and assist me in solving my issue, that'd be great. Also, this is my first time posting here, so sorry if I am a bit messy with everything.
The error was here:
cache: 'false';
The correct usage is:
cache: false;
These quotes caused cache to be kept, meaning that the quotes didn't change.

multiple ajax calls is causing mixed datasets

I've been developing a phonegap application which uses jQuery Mobile for it's main structure.
When the site/app runs, it executes a number of ajax calls to get the latest data to the app. For example, a list of items is gathered for the homepage, whilst other lists of other items are gathered for other pages.
What I am finding is that every now and then there is a mixup in data.
As a random (but applicable) example:
Query 1 - get names and photos of people
Query 2 - get names and photos of cities/locations
In each of the ajax calls, instead of using (data, status) I have renamed the data object to a unique identifier hoping this would resolve the issue.
Then, on my $.each function I have ensured that the iterator has a different name too, so instead of (i, item) it might be (i, personitem) and (i, cityitem)
The Issue
Despite my best attempts to get this data to not have any possibility of crossover, I'm finding that (to keep with the current example) - photos of people will show up on the cities page, and photos of cities will show up on the users page.
This is also an intermittent issue. Sometimes it won't happen at all, other times it will happen a lot or only a little bit.
I hope I have explained myself clearly. Thank you in advanced to anyone willing to help! I'm all out of ideas :-(
==================
UPDATE
My main question is if anyone knows what might cause data-mixups in such queries.
My queries all look like this:
$.ajax({
url: 'get_cities.php?country='+country,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(citydata, status){
if(citydata.length == 0){
$('#somediv').append('no data to show');
}
$.each(citydata, function(i,cityitem){
var content = '<img src="'+cityitem.image+'" />'
+'<p>'+cityitem.name+'</p>';
$('#somediv').append(content);
}
});
At this point I believe #mason81 was correct with his suggestion.
I removed all of the:
jsonp: 'jsoncallback',
in my code, and then updated my PHP files to use
echo $_GET['callback'] . '(' . json_encode($records) . ');';
instead of
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
I originally also placed &callback=? into my URL's but from reading the jQuery Ajax documentation it should automatically assign a random unique callback to each call as long as you are using dataType: jsonp without manually specifying a callback parameter.
If this fails I'll still consider this the correct answer, I'll probably just have to go through and either assign unique callback parameters to each request or ammend my URL's with &callback=? as mentioned above.
Thanks everyone for their input!

CRM 2011 API call for a view GUID by name

I'm trying to pull back the GUID of a view to set a default lookup value in javascript. The rest of my code works if I hard code the variables, but that's not good development practice (though, pulling back a unique identifier by querying on a non-unique identifier isn't great either, but its better). I'm not sure how to form the ajax call though.
Here is a shell of what I am working with, I just don't know what to put at the end of /CRMServices/2011/OrganizationData.svc/ to get the proper record from the API. The Views are savedquery entities, so /savedquerySet makes sense but I'm not sure how to tell it to look up by name. I've not used this API a lot, and the documentation is confusing for me.
var b = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/savedquerySet (<something here not sure what>)";
$.ajax({
type: "GET",
datatype: "json",
url: b,
beforeSend: function (a) {
a.setRequestHeader("Accept", "application/json")
},
success: function (a) {
var b = a.d;
SetGuid(b.SavedQueryIdUnique); // defined function
}
})
the field I am trying to query on is Name.
Help is very appreciated. This is in CRM 2011 UR 8 or so
Your REST query should look something like this:
/SavedQuerySet?$select=SavedQueryId&$filter=Name%20eq%20'YOUR VIEW NAME HERE'
The SavedQuerySet name is case sensitive, as well as the attribute name in the select (and filter) clause.
See the MSDN documentation on the ODATA endpoint for details.

json "invalid label" - when parsing google Distance Matrix Request

I'm having hard time with this simple ajax call
function sendreq()
{
$.ajax({
dataType: 'jsonp',
url: 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=Seattle&destinations=San+Francisco&mode=driving&sensor=false',
success: function (jsonp)
{
alert('success');
}
});
}
I'm able to see the api result in json format when i hit the url from browser and seems like jQuery sees the result too but is unable to parse.
it throws an error
invalid label "destination_addresses" : [ "San Francisco, CA, USA" ],
im using jQuery 1.7.1. from ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
any help would be appreciated
thanks.
You can't get Distance Matrix's data by Ajax, because of Same Origin Policy. If you are using Google Distance Matrix API , the only way you can retrieve that data, is from your server-side script. The other method is, you can use Distance Matrix Service. For both methods(API and Service) you have to notice Usage Limits and Requirements:
Use of the Distance Matrix service must relate to the display of
information on a Google Map; for example, to determine
origin-destination pairs that fall within a specific driving time from
one another, before requesting and displaying those destinations on a
map. Use of the service in an application that doesn't display a
Google map is prohibited.
Maybe you need to use the JavaScript API?
http://www.quora.com/Why-doesnt-the-Google-Maps-API-support-JSONP,
http://blog.futtta.be/2010/04/09/no-more-jsonp-for-google-geocoding-webservice

Categories