Cordova GeoLocation not applying lat long to json get - json

I'm using the Cordova Geolocation plugin to get the users lat and long data. The intention is use that lat and long and apply it to an api call I'm making to Breezometer. Unfortunately my code is is not working correctly. Can someone let me know what im missing here:
.controller('GeoCtrl', function($cordovaGeolocation, $scope, $http) {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude
var long = position.coords.longitude
$scope.result = "";
$http.get('https://api.breezometer.com/baqi/?lat='+ lat + 'lon=-' + long + '&key=c329a5b015f442748e088cfd13726267')
.success(function(data, status, headers,config){
console.log('data success');
console.log(data); // for browser console
$scope.result = data; // for UI
})
.error(function(data, status, headers,config){
console.log('data error');
})
.then(function(result){
things = result.data;
});
}, function(err) {
// error
});
var watchOptions = {
frequency : 1000,
timeout : 3000,
enableHighAccuracy: false // may cause errors if true
};
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function(err) {
// error
},
function(position) {
var lat = position.coords.latitude
var long = position.coords.longitude
});
watch.clearWatch();
// OR
$cordovaGeolocation.clearWatch(watch)
.then(function(result) {
// success
}, function (error) {
// error
});
})

The url for your http request is wrong.
Try the following,
$http.get(https://api.breezometer.com/baqi/?lat='+ lat + '&lon='+ long +'&key='+ key)
You have miised & in between lat and lon. And lon need not be prefixed with -
Example:
https://api.breezometer.com/baqi/?lat=13.082680199999999&lon=80.2707184&key=c329a5b015f442748e088cfd13726267
Click here to view the results.

Related

google maps click event isn't reading objects from data

I'm trying to get latitude and longitude by clicking on map then I use them to get formatted address from google maps API and finally I want to persist lat, lng and formatted address in my object "station" declared in data
data() {
return {
station: {},
mapName: this.name + "-map",
lat: Number,
lng: Number,
Fulladdress: String
};
} ,
mounted() {
const element = document.getElementById(this.mapName);
const options = {
zoom: 14,
center: new google.maps.LatLng(51.501527, -0.1921837)
};
const map = new google.maps.Map(element, options);
google.maps.event.addListener(map, "click", function(event) {
this.lat = event.latLng.lat();
this.lng = event.latLng.lng();
axios
.get(
"https://maps.googleapis.com/maps/api/geocode/json?latlng=" +
this.lat +
"," +
this.lng +
"&key=APIKEY"
)
.then(resp => {
var fulladdress;
console.log(resp.data.results[0].formatted_address);
fulladdress = resp.data.results[0].formatted_address;
this.Fulladdress = fulladdress;
//persist lat, lng and formatted address in my object station
this.station.address = this.Fulladdress;
this.station.lat = this.lat;
this.station.lng = this.lng;
})
.catch(e => {
console.log(e);
});
});
}
The context is changing. Inside the click handler, the this is not referring to the Vue instance, but something else (it depends on how google maps does it, but it could be window or the map instance).
To have the this be the Vue instance, use arrow functions instead.
Change from:
google.maps.event.addListener(map, "click", function(event) {
To:
google.maps.event.addListener(map, "click", (event) => {

Center map on user's location (Google Maps API v3)

I've looked a lot of various other reports about this problem, but I can't find the solution to get the location of user.
Here is my code:
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true'>
</script>
<script>
// prepare variables
var main = document.getElementById('main');
// async XHR request
var xhReq = new XMLHttpRequest();
xhReq.open('GET','../data/data.json', true);
xhReq.onload = function (e) {
if ((xhReq.readyState === 4) && (xhReq.status === 200)) {
// prepare external data
var data = JSON.parse(xhReq.responseText);
// prepare map
var map;
// var bounds = new google.maps.LatLngBounds();
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(54.6867151,25.2803843)
};
map = new google.maps.Map(main,mapOptions);
// add all data to the map
for(i=0;i<data.length;i++){
// loc = new google.maps.LatLng(data[i].lat,data[i].lng);
// bounds.extend(loc);
window['marker'+i] = new google.maps.Marker({
position: new google.maps.LatLng(data[i].lat,data[i].lng),
map: map,
title: data[i].name,
articles: data[i].articles
}
);
// add onClick function
google.maps.event.addListener(window['marker'+i], 'click', function() {
// magic should be here
var data = this.articles;
var list = document.getElementById('list');
var main = document.getElementById('main');
list.innerHTML = '';
list.style="width:25%;";
for(i=0;i<data.length;i++){
list.innerHTML += '<a href="' + data[i].url + '" target="_blank"><div class="listImg" style="background-image:url(' + data[i].img + ');"><\/div><span class="topic">(' + data[i].topic + ')<\/span> <h1>' + data[i].name + ' <\/h1><span class="date">(' + data[i].date + ')<\/span><\/a>';
};
});
};
// recenter + rezoom
// map.fitBounds(bounds);
// map.panToBounds(bounds);
};
};
xhReq.send(null);
</script>
It sets the center of map to exact coordinates which are in code.
Thanks for your support.
English isn’t my first language, so please excuse any mistakes.
Getting the user location is a browser feature that most modern browsers support. However, you still need to test for the ability to get the location in your code.
if (navigator.geolocation) { // test for presence of location feature
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
console.log('user denied request for position');
});
} else {
console.log('no geolocation support');
}

JSON.parse() fails with unexpected token using Songkick API

I'm trying to parse a response from the Songkick API with the following in Node:
router.post('/', function(req, res) {
var artist = req.body.artist;
var id;
res.render('artist', { title: 'Artist', artist: artist });
http.request({host: 'api.songkick.com', path: '/api/3.0/search/artists.json?query=' + artist + '&apikey=myAPIKey'}, function(res) {
res.on("data", function(chunk) {
id = JSON.parse(chunk).resultsPage.results.artist[0].id;
console.log(id);
http.request({host: 'api.songkick.com', path: '/api/3.0/artists/' + id + '/gigography.json?apikey=Z2JWQTvgk4tsCdDn'}, function(res) {
res.on("data", function(chunk) {
console.log(JSON.parse(chunk).resultsPage.results);
});
}).end();
});
}).end();
});
However, JSON.parse fails with SyntaxError: Unexpected token t (the last character changes depending on the artist requested).
Here's an example API response.
How can I fix the syntax error?
basically the same as the other answer. you need to concat the chunks of data and register for an end event and do the parsing there.
Here's one I tried and it seems to work as expected.
var http = require('http');
var artist = 'Beatles'
http.request({host: 'api.songkick.com', path: '/api/3.0/search/artists.json?query=' + artist + '&apikey=Z2JWQTvgk4tsCdDn'}, function(res) {
var response_data = '';
var id;
res.on("data", function(chunk) {
response_data += chunk;
});
res.on('end', function(){
id = JSON.parse(response_data).resultsPage.results.artist[0].id;
console.log(id);
http.request({host: 'api.songkick.com', path: '/api/3.0/artists/' + id + '/gigography.json?apikey=Z2JWQTvgk4tsCdDn'}, function(res) {
var inner_data = '';
res.on("data", function(chunk) {
inner_data += chunk;
});
res.on("end", function(){
console.log(JSON.parse(inner_data).resultsPage.results);
});
}).end();
});
}).end();
I would try to concat the string (arriving in chunks) and then use the end event. Like:
router.post('/', function(req, res) {
var artist = req.body.artist;
var id;
var data1 = '';
res.render('artist', { title: 'Artist', artist: artist });
http.request({host: 'api.songkick.com', path: '/api/3.0/search/artists.json?query=' +
artist + '&apikey=myAPIKey'}, function(res) {
res.on("data", function(chunk) {
data1 += chunk;
});
res.on('end', function(){
id = JSON.parse(data1).resultsPage.results.artist[0].id;
console.log(id);
var data2 = '';
http.request({host: 'api.songkick.com', path: '/api/3.0/artists/' + id + '/gigography.json?apikey=Z2JWQTvgk4tsCdDn'}, function(res) {
res.on("data", function(chunk) {
data2 += chunk;
});
res.on('end', function(){
console.log(JSON.parse(data2).resultsPage.results);
});
}).end();
});
}).end();
});
Basically, it is using data1 and data2 as buffers and calls your function only when all data has arrived.

Unable to clear markers using setMap(null) or setVisible(false) in the google map

I have using knockout javascrit for the Google Map but i cant clear markers on the map, i have got error message there, error following
> Ripple :: Environment Warming Up (Tea. Earl Gray. Hot.) ripple.js:37
> web :: Initialization Finished (Make it so.) ripple.js:37 Uncaught
> TypeError: Object [object Object] has no method 'dxmap' Shops.js:70
> eula response: true ripple.js:47 Uncaught TypeError: Object [object
> Object] has no method 'dxmap' Shops.js:70 Uncaught TypeError: Object
> #<Object> has no method 'setMap' Shops.js:137
My code below could you please help me
function FetchNearestShops(latitud,longitud)
{
$.ajax({
type: 'POST',
async:false,
contentType: 'application/json',
dataType: 'jsonp',
url: url + "/GetNearestShop",
//data: { Latitude: 9.998472, Longitude: 76.308059 },
data: { Latitude: latitud, Longitude: longitud },
success: function (data) {
loc.removeAll();
productsNear.removeAll();
$.map(data, function (item) {
loc.push({ label: item.ShopName, location: [item.Latitude, item.Longitude] });
//productsNear.push({ Name: item.ShopName, IsFavorite: false, Address: "", id: item.ShopId, Image: "mockcontent/shopimages/1.jpg" });
productsNear.push({ Name: item.ShopName, IsFavorite: item.Isfavourite, Address: item.Address, id: item.ShopId, Image: item.ImageUrl });
});
alert();
viewModel.options.markers = loc;
},
error: function () {
alert("error");
}
});
}
function SetLocation() {
var geocoder = new google.maps.Geocoder();
//var address = "ernakulam";
//alert(viewModel.options.location());
geocoder.geocode({ 'address': txtAddress() }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
ClearMap();
FetchNearestShops(latitude, longitude);
}
});
}
function ClearMap()
{
var markers = viewModel.options.markers();
for (var i = 0; i < markers.length; i++) {
markers[i];
markers.setMap(null);
}
markers;
}
I think you have problem in loop of your ClearMap() function. Try
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
Instead markers.setMap(null);.
Also i'm no sure what your markers it is correct collection of Google Markers.
This collection should look something like this:
markers[i] = new google.maps.Marker({
position: new google.maps.LatLng('some latitude', 'some longitude'),
map: map, //object of Google Map
name: 'Marker Name'
});

Reverse geocoding from google maps API

I use the Google Maps API to save a database of addresses in a point.
Came across a problem which is the third day I can not decide. Can you give me some advise.
I cycle runs through all the points, which are marked on the map, in which using geotsoder.geoсode recognize and and use ajax write this address in the database.
Example:
function saveAddress(marker_points)
{
var i = 0;
id = 0;
address = [];
var count = 0;
points = [];
for(i in marker_points)
{
var geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': marker_points[i]},function(results, status){
address = results[0].formatted_address;
});
$.ajax({
type: "POST",
url: "/user.view.location.phone_id-{/literal}{$iPhoneId}{literal}.html",
cache: false,
data: "address=" + address + "&location_point=" + marker_points[i],
dataType: "html",
async: false,
timeout: 5000,
success: function (data) {
}
});
}
}
But in Ajax passed last point, ie written in the database returned last address and the last point on which this address.
Could you tell me what could be the problem and how to solve it, because he had tried all the options, it does not work?
You can use function closure to associate the request with the response.
Example using geocoded addresses:
They function that gets closure on "i" is:
function geocodeAddress(i) {
geocoder.geocode({'address' : locations[i]},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
createMarker(results[0].geometry.location, i);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
I think your script may sometimes call ajax method before getting response from geocoder.geocode. Try to put $.ajax method inside of
function(results, status){
address = results[0].formatted_address;
}
so that fragment of your code would look something like:
var marker_points = ["50.463425,30.508120","50.465822,30.514380","50.465317,30.515609"];
for(i in marker_points) {
codeAndSendAddress(marker_points[i]);
}
function codeAndSendAddress(point){
var mp = point.split(',');//Extract numbes from string
var latLng = new google.maps.LatLng(mp[0],mp[1]) // create latitude/logitude object
geocoder.geocode( { 'latLng': latLng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) { make sure location was found
var geocodedAddress = results[0].formatted_address;
var geocodedLocationPoint = results[0].geometry.location;
$.ajax({
type: "POST",
url: "/user.view.location.phone_id-{/literal}{$iPhoneId}{literal}.html",
data: 'address='+geocodedAddress+
'&geocoded_location_point='+geocodedLocationPoint+
'&location_point='+point,
timeout: 5000,
success: function (data) {}
});
}
});
}