get Lat, Lng, Country and State together from Google Maps Autocomplete js - javascript

I need from Google Place Autocomplete these values:
alert(
place.name + // Works
place.geometry.location.lat() + // Works
place.country + // Not works - what is correct value to get country value?
place.state // Not works - what is correct value to get state value?
);
It works for place.name and place.geometry, but it not works for place.country and place.state.
How to get also the other two values? Thank you for any advice.
Whole function:
function initializeGoogleMaps() {
var input = document.getElementById("googleMapsSearch");
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(
autocomplete,
"place_changed",
function() {
var place = autocomplete.getPlace();
alert(
place.name + // Works
place.geometry.location.lat() + // Works
place.country + // Not works - what is correct value to get country value?
place.state // Not works - what is correct value to get state value?
);
document.getElementById("city").value = place.name; // Works
document.getElementById("cityLat").value = place.geometry.location.lat(); // Works
document.getElementById("country").value = place.country; // Not works
document.getElementById("state").value = place.state; // Not works
});
}

You can get the state and the country under the address_components array returned by the getDetails() method. Since the address components is being returned as an array, you can parse the results like this:
var country;
var state;
var components = place.address_components;
for(i=0;i<components.length;i++){
if(place.address_components[i].types[0].toString() === 'administrative_area_level_1'){
state = place.address_components[i].long_name;
}else if(place.address_components[i].types[0].toString() === 'country'){
country = place.address_components[i].long_name;
}
}
Note: administrative_area_level_1 usually signifies to the state and varies depending on the political heirarchy of a certain country.
Here's a complete sample you can refer to. You just need to replace "YOUR_API_KEY" with your own API key.
For more information regarding Place details results, please checkout this link: https://developers.google.com/maps/documentation/javascript/places#place_details_results
Hope this helps!

Related

Trouble getting a specific field from OpenWeatherMap API's output, via JS / XMLHttpRequest

So I'm building this web forecast app using OpenWeatherMap API, and so far I'm being able to fetch the data from the first iteration of the list's output, however I need to obtain the data of other specific fields aswell. Here's a bit of my code:
ajaxGet("https://api.openweathermap.org/data/2.5/onecall?lat=4.6097&lon=-74.0817&exclude=current,minutely,hourly,alerts&appid=APPID&units=metric", function (response) {
var data = JSON.parse(response);
console.log(data);
var temperature = document.createElement("h6");
temperature.textContent = data.daily[0].temp.max + "°" + " / " + data.daily[0].temp.min + "°";
document.getElementById("temperaturaBogVier").appendChild(temperature);
});
And here's an example of what the API's output looks like (I'm only showing the first iteration in here, but there are at least 6 in total, https://api.openweathermap.org/data/2.5/onecall?lat=4.6097&lon=-74.0817&exclude=current,minutely,hourly,alerts&appid=APPID&units=metric):
{"lat":4.61,"lon":-74.08,"timezone":"America/Bogota","timezone_offset":-18000,"daily":
[
{"dt":1600876800,
"sunrise":1600857917,
"sunset":1600901504,
"temp":{"day":18.14,"min":8.99,"max":18.14,"night":12.08,"eve":15.45,"morn":8.99},
"feels_like":{"day":17,"night":11.02,"eve":14.6,"morn":7.58},
"pressure":1017,"humidity":54,
"dew_point":8.69,
"wind_speed":1.2,
"wind_deg":164,
"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],
"clouds":82,
"pop":0.94,
"rain":5.85,
"uvi":15.14}
]
}
So as you can see, I'm being able to print into my HTML the data contained into "data.daily[0].temp.", but it only works for the first set of fields and I got no clue how to select a specific iteration. I'm sure I'm missing something into the concat, but nothing I've tried has worked so far.
Any help would be greatly appreciated, and rewarded with an imaginary waffle. THX :D
The temperatures for each day data.daily are defined as an JavaScript array of objects. You can simply access them by their index, which indicates their position in the array.
data.daily[0] // First element
data.daily[1] // Second element
data.daily[2] // Third element
Once you have selected an object within the array, you can then access certain values like data.daily[2].temp.max.
The cool thing about arrays is that you can iterate them with a loop. This will save you a lot of writing, if you want to print out each temperatures for every day:
ajaxGet("https://api.openweathermap.org/data/2.5/onecall?lat=4.6097&lon=-74.0817&exclude=current,minutely,hourly,alerts&appid=YOUR_API_KEY_HERE&units=metric", function (response) {
var data = JSON.parse(response);
console.log(data);
data.daily.forEach(function (date) {
var temperature = document.createElement("h6");
temperature.textContent = date.temp.max + "°" + " / " + date.temp.min + "°";
document.getElementById("temperaturaBogVier").appendChild(temperature);
})
});
Please note: I've removed the appid=XXXXX part of the request URL, because it contains your personal API key for OpenWeather, which you should not share publicly.
If I understand the question correctly, you want to take all daily max/min-values and put them into elements that you want to append to another element.
Here is a way to do that
ajaxGet("https://api.openweathermap.org/data/2.5/onecall?lat=4.6097&lon=-74.0817&exclude=current,minutely,hourly,alerts&units=metric", function (response) {
var data = JSON.parse(response);
console.log(data);
data.daily
.map(datapoint => datapoint.temp) //get the temp value/object from each datapoint
.map(temp => { //create an element and add each max/min value to that element's textContent
const temperature = document.createElement("h6");
temperature.textContent = temp.max + "° / " + temp.min + "°";
return temperature;
})
.forEach(element => { //add each of the elements created in the previous map to the desired element
document.getElementById("temperaturaBogVier").appendChild(element);
});
});
As pointed out in the other answer, I've also removed the app-id query parameter

Make changes of colors of icons visible in openlayers with a function

I try to accomplish that I will be able to change the color of marker icons to be visible in the map. They are in the map in different colors. Those colors are correspondenting to the json cat_id key's.
1: "http://dev.openlayers.org/img/marker.png",
2: "http://dev.openlayers.org/img/marker-blue.png",
3: "http://dev.openlayers.org/img/marker-gold.png",
4: "http://dev.openlayers.org/img/marker-green.png",
Each marker icon that is in the map is getting it's position, color and other valuable data from the json objects in the data id in the script tag. I didn't code the part of that work's close with the openlayer libary's. I wrote the following part of the total of the script:
var json = document.getElementById('data').innerHTML;
json = JSON.parse(json); // converts text into JSON
// search criteria (could be changed)
var $search_postal = "8912JB";
var $search_number = "10";
var $change_cat = 1;
function changeColor() {
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (json[key].postal == $search_postal) {
if (json[key].number == $search_number) {
alert("Gonna change cat_id " + json[key].cat_id + " of the number search string " + $search_number + " of the postal search string " + $search_postal + " to cat_id " + $change_cat);
json[key].cat_id = "1";
alert('Changed!');
const posts = json; // the constant that is used to display the icons
var myJSON = json;
document.getElementById('demo').innerHTML = JSON.stringify(myJSON, undefined, 2); // changes of the json data to see on screen
}
}
}
}
}
const posts = json; //the constant that is used to display the icons
var myJSON = JSON.stringify(json);
document.getElementById('demo').innerHTML = myJSON;
This script will change the cat_id of the given search input. In the example it does a search for postal 8912JB with number 1. Once it has made the loop to find it's position it will change the cat_id value of 3 to 1. In other words the json data has been changed. Since it is stored in the const posts I replace this cons with the changed data. My problem is that I'm unable to refresh the marker icon(s) in the map with the new json data that is changed (cat_id: 1 of postal 8912JB number 10). This has to do with less knowledge about openlayers and Javascript. I'm struggling already 2 weeks with this. Can anybody help me to accomplish this? If it changes from color is the only thing that is required. I would only need to give the changes to the variables $search_postal, $search_number and $change_cat.
Here is the page for debug: https://jsfiddle.net/j4z1vpht/4/
Thanks for any help,
grid
You need to update the new category to the map feature, like this:
const updateFeatureCategory = (featureId, categoryId) => {
const feature = marker_layer.getSource().getFeatureById(featureId);
const post = feature.get("post");
const updatedPost = {
...post,
cat_id: categoryId
}
feature.set("post", updatedPost);
}
function changeColor() {
...
json[key].cat_id = "1";
updateFeatureCategory(key, "1");
...
}
Here's a working fiddle: https://jsfiddle.net/wsm2h3qz/1/

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.

Javascript API - Error 401 - Missing api_id when clicking on SearchBox

I have two symptoms that make me think there's something wrong with my Nokia appId/token. One is that when I try to use the searchbox, I get a javascript error "Error 401 - Missing api_id". The second is when I go to developer.here.com and to My Apps, and look at the hit history of my app, I see zero hits. What am I doing wrong?
nokia.Settings.set("appId", "[My ID]");
nokia.Settings.set("authenticationToken", "[MY TOKEN]");
var my_lat = 41.88
var my_lon = -87.63
map = new nokia.maps.map.Display(document.getElementById('mapcanvas'), {
'components': [
// Behavior collection
new nokia.maps.map.component.Behavior(),
new nokia.maps.map.component.ZoomBar(),
new nokia.maps.map.component.Overview(),
new nokia.maps.map.component.TypeSelector(),
new nokia.maps.map.component.ScaleBar()
],
'zoomLevel': 11, // Zoom level for the map
'center': [my_lat, my_lon] // Center coordinates
});
// Initialize search box:
var searchBox = new nokia.places.widgets.SearchBox ({
targetNode: 'searchbox',
searchCenter: function () {
return {
latitude: my_lat,
longitude: my_lon
}
},
onResults: function (data) {
renderResults (data);
}
});
// Handle the results of the search. This callback function
// receives the raw places data as an array. For each element
// in this array, it creates an HTML list element and fills
// it with the name of the place:
function renderResults (data) {
var previewList = document.getElementById ('results');
previewList.innerHTML = '';
var results = data.results.items;
for (var i = 0, l = results.length; i < l; i++) {
var result = results[i];
var resultLi = document.createElement ('li');
resultLi.innerHTML = result.title;
previewList.appendChild (resultLi);
}
}
The problem was how I was getting the javascript lib.
This is what worked. Note the "with=maps,places".
<script type="text/javascript" src="http://api.maps.nokia.com/2.2.4/jsl.js?with=maps,places"></script>
Here's what did not work
<script type="text/javascript" src="http://api.maps.nokia.com/2.2.4/jsl.js"></script>
<script type="text/javascript" src="http://api.maps.nokia.com/2.2.4/jsl.js?with=places"></script>
Your code looks correct - my assumption would be that the appId and token you are using are not valid.
Firstly to prove this is the case start with the code behind the Places Widget example. Copy the code to your PC or local server and see if you can get a local copy working for you - if you type the word Airport into the search box you should get suggestions appearing after the first three letters, and markers on the map once you click search.
Now try replacing the app id and token wih blanks:
nokia.Settings.set("appId", "");
nokia.Settings.set("authenticationToken", "");
The application should no longer work. If this is also the case when you enter your appId and token then it looks like you have incorrectly copied them, used the app name by mistake (or something is up with the back-end).
The most comprehensive guide to creating a new appId and token can be found here - I would follow it from scratch and create a new one if necessary. When logged in and you click on Manage Apps the appId and token can be found in the boxes on the right. Double click on the box to select all and ensure that you don't inadvertently miss the final character which may not quite fit in the box.
Go back to your working demo example and replace the demo appId and token with the ones associated with your account. Hopefully it should now work for you.

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