How to merge two different object from JSON data - angularjs

Hi I need some help with this code snippet. The output that I get is multiple different objects of JSON data. But I want to extract the destination data then merge them as an array. But all the data I get is only one data merge as an array, one by one.
Here is the output:
$scope.findHospital = function(){
$ionicLoading.show({
template: '<ion-spinner icon="bubbles"></ion-spinner><br/>Acquiring location!'
});
var posOptions = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 0
};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var infowindow;
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: myLatlng,
radius: 5000,
type: ['police']
}, callback);
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, long);
geocoder.geocode({'latLng': latlng}, function(results, status) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
console.log(details);
var url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+results[0].formatted_address+"&destinations="+details.formatted_address+"&key=AIzaSyDDxMGpu5SP5XwZGrKw5BQWl_r2dgLgpPY";
var distances = [];
$http.get(url).then(function(response){
var str = response.data.rows[0].elements[0].distance.text;
distances = distances.concat(str);
console.log(distances);
});
}
});
}
}
}
CODE UPDATED!

I strongly suspect, distances array is initializing everytime when createMarker method is called. So, put your distances in global scope. i.e. just above your resolving getCurrentPosition promise.
var distances = [];
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
// your code
and remove distances intialization from inner code.

This is what you need!! A array outside of your function createMarker. When you call $http.get, you should concatenate the response with your distances array.
var distances = []; // HERE
function createMarker(place) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, long);
geocoder.geocode({'latLng': latlng}, function(results, status) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
var url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+results[0].formatted_address+"&destinations="+details.formatted_address+"&key=AIzaSyDDxMGpu5SP5XwZGrKw5BQWl_r2dgLgpPY";
$http.get(url).then(function(response){
var str = response.data.rows[0].elements[0].distance.text;
distances = distances.concat(str); // HERE
});
}
});
}

Related

Only getting a few markers in the map

I am very new to angularJS and still exploring.I have created a map and showing around 1500 markers in it but when I load only 11 markers are visible.I am taking the Zip codes from a XML file and using geocoding I am converting them to LatLng and showing in map.Can any one suggest any solution.
Thanks in advance.
//Angular App Module and Controller
var mapApp = angular.module('mapApp', []);
// app.directive("importSheetJs", [SheetJSImportDirective]);
mapApp.factory('mySHaredService', function ($rootScope) {
var mySHaredService = {};
mySHaredService.message = '';
mySHaredService.prepForBroadcast = function (msg) {
this.message = msg;
this.broadcastItem();
};
return mySHaredService;
});
mapApp.controller('MapController', function ($scope, $timeout, $window, $rootScope, mySHaredService) {
//Parsing data from XML
$rootScope.zipArray = [];
var url = "location.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
$rootScope.LatLongList = [{
"latitudeValue": "",
"longitudeValue": ""
}];
oReq.onload = function (e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = "K1";
var worksheet = workbook.Sheets[first_sheet_name];
data = JSON.stringify(XLSX.utils.sheet_to_json(worksheet));
console.log("Messege data" + data);
var finalData = JSON.parse(data);
for (var i = 0; i <= finalData.length; i++) {
// console.log("Zip code is " + finalData[i].Zip);
$rootScope.zipArray.push(finalData[i].ZIP);
console.log("Zip code inside zip array is " + $rootScope.zipArray[i]);
}
}
setTimeout(function () {
$scope.$apply(function () {
})
}, 17770);
$timeout(function() {
console.log("Zip data from excel sheet" + $rootScope.zipArray)
var geocoder = new google.maps.Geocoder();
for (var i = 15; i <= $rootScope.zipArray.length; i++) {
var address = $rootScope.zipArray[i];
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
$rootScope.LatLongList.push({
"latitudeValue": latitude,
"longitudeValue": longitude
});
}
});
}
// setTimeout(function () {
// $scope.$apply(function () {
// })
// }, 30000);
$timeout(function () {
console.log("Latitude value " + $rootScope.LatLongList[1].latitudeValue)
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(33.6496252, -117.9190418),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
var circle = new google.maps.Circle({
center: new google.maps.LatLng(33.6496252, -117.9190418),
map: $scope.map,
radius: 10000, // IN METERS.
fillColor: '#FF6600',
fillOpacity: 0.3,
strokeColor: "#FFF",
strokeWeight: 0 // DON'T SHOW CIRCLE BORDER.
});
var bounds = circle.getBounds();
$scope.markers = [];
$rootScope.selectedAd = "";
var selectedLocation = [{ "lat": 0, "long": 0 }];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (info) {
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.latitudeValue, info.longitudeValue),
title: ""
});
marker.content = '<div class="infoWindowContent">' + '<br />' + info.latitudeValue + ' E,' + info.longitudeValue + ' N, </div>';
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent('<h2>' + marker.title + '</h2>' +
marker.content);
infoWindow.open($scope.map, marker);
selectedLocation[0].lat = marker.getPosition().lat();
selectedLocation[0].long = marker.getPosition().lng();
console.log("Latitude is " + selectedLocation[0].lat + "Longitude is " + selectedLocation[0].long);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
latLng: marker.getPosition()
}, $scope.selectedLoc = function (responses) {
if (responses && responses.length > 0) {
// alert(responses[0].formatted_address);
$rootScope.selectedAd = responses[0].formatted_address;
setTimeout(function () {
$scope.$apply(function () {
$rootScope.selectedAd = responses[0].formatted_address;
})
}, 1000);
$timeout(function () {
$rootScope.selectedAd = responses[0].formatted_address;
$scope.handleClick = function (msg) {
mySHaredService.prepForBroadcast($rootScope.selectedAd);
}
$scope.$on('handleBroadcast', function () {
$scope.message = $rootScope.selectedAd;
})
}, 2000);
} else {
}
});
});
$scope.markers.push(marker);
}
setTimeout(function () {
}, 3000);
$timeout(function () {
for (i = 1; i < $rootScope.LatLongList.length; i++) {
console.log(bounds.contains(new google.maps.LatLng($rootScope.LatLongList[i].latitudeValue, $rootScope.LatLongList[i].longitudeValue)));
// if (bounds.contains(new google.maps.LatLng($rootScope.LatLongList[i].latitudeValue, $rootScope.LatLongList[i].longitudeValue))) {
createMarker($rootScope.LatLongList[i]);
console.log("The value of i is " + i);
// }
}
}, 4000);
$scope.openInfoWindow = function (e, selectedMarker) {
var data = $rootScope.selectedAd
this.broadcastItem();
window.location = "valuePage.html";
}
}, 4000);
}, 2000);
oReq.send();
});
mapApp.controller("viewApp", function ($scope, $rootScope, mySHaredService, $timeout) {
// $scope.selectedAd = Products.FirstName;
// $scope.selectedAd = Products.FirstName;
setTimeout(function () {
$scope.$on('handleBroadcast', function () {
$scope.message = mySHaredService.message;
});
}, 3000);
$timeout(function () {
$scope.$on('handleBroadcast', function () {
$scope.message = mySHaredService.message;
});
}, 4000);
});
This is because you are sending too many requests through per second.
In addition to daily quota limits, the geocoding service is rate limited to 50 QPS (queries per second), calculated as the sum of client-side and server-side queries.
The Optimizing Quota Usage When Geocoding has a lot of strategies on how to account for that.
In your case I suggest doing a randomized interval for each request you make that way they are spread out you avoid going over the 50 request per second limit.
I've modified the part of your code sample where you are making the request.
mapApp.controller('MapController', function ($scope, $timeout, $window, $rootScope, mySHaredService) {
//Parsing data from XML
$rootScope.zipArray = [];
var url = "location.xlsx";
var randomTime = Math.round(Math.random()*(3000-500))+500;
var geocodeRequest = setTimeout(function() {
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
$rootScope.LatLongList = [{
"latitudeValue": "",
"longitudeValue": ""
}];
oReq.onload = function (e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = "K1";
var worksheet = workbook.Sheets[first_sheet_name];
data = JSON.stringify(XLSX.utils.sheet_to_json(worksheet));
console.log("Messege data" + data);
var finalData = JSON.parse(data);
for (var i = 0; i <= finalData.length; i++) {
// console.log("Zip code is " + finalData[i].Zip);
$rootScope.zipArray.push(finalData[i].ZIP);
console.log("Zip code inside zip array is " + $rootScope.zipArray[i]);
}
}
setTimeout(function () {
$scope.$apply(function () {
})
}, 17770);
}, randomTime);

How to get coordinates values while long tap/hold in ionic google maps

I am trying to get coordinates while tap or hold events in ionic from the Google Maps.
While holding I am getting values in browser console not getting in device.
How to clear this issue?. I need to get values while holding/taping in mobile apps using ionic framework [google maps].
Any help would be appreciated.Thanks in advance.
.controller('HomeCtrl', function ($scope, $rootScope, $cordovaGeolocation, $ionicLoading, $ionicGesture) {
$ionicLoading.show({
template: '<ion-spinner icon="bubbles"></ion-spinner><br/>Acquiring location!'
});
var posOptions = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 0
};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
$rootScope.currentlat = lat;
$rootScope.currentlong = long;
var myLatlng = new google.maps.LatLng(lat, long);
$rootScope.myLatlng = myLatlng;
var mapOptions = {
center: myLatlng,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
$scope.map = map;
marker = new google.maps.Marker({
position: myLatlng,
map: $scope.map
});
var element = angular.element(document.querySelector('#map'));
$ionicGesture.on('hold', function(e){
$scope.$apply(function() {
alert('hold happens');
google.maps.event.clearListeners(map, 'click');
google.maps.event.addListener(map, 'click', function(event) {
alert(event.latLng);
});
});
}, element);
google.maps.event.addListener(marker, "click", function (event) {
});
$ionicLoading.hide();
}, function (err) {
$ionicLoading.hide();
console.log(err);
});
}
I think your problem is that your using
$ionicGesture.on('hold')
Iconic uses Cordova and Cordova google maps has its own event handler as the "map" is in native view not JavaScript related. You can read up in more detail here.
So once your device is ready
var map = new google.maps.Map(document.getElementById("map"), mapOptions),
longClick = plugin.google.maps.event.MAP_LONG_CLICK;
map.on(longClick, function (latLng) {
var selectedLatLocation = latLng.lat.toString();
var selectedLongLocation = latLng.lng.toString();
alert(selectedLatLocation, selectedLongLocation);
});

multiple marker doesn't show up in google map using angualrjs

.controller('homeCtrl', function($scope, Markers) {
var username = window.localStorage.getItem('username');
var id_user = window.localStorage.getItem('id_user');
console.log(username);
console.log(id_user);
document.getElementById('usernameArea').innerHTML = username;
var map = null;
google.maps.event.addDomListener(window, 'load', function() {
var myLatlng = new google.maps.LatLng(-7.977467753377946, 112.63355255126953);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
navigator.geolocation.getCurrentPosition(function(pos) {
map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
//var tes = new google.maps.Latlang();
//var tes = map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
var tes = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
console.log(tes.lat(), tes.lng());
//console.log(tes.lng());
window.localStorage.setItem('lat',tes.lat());
window.localStorage.setItem('lng',tes.lng());
var myLocation = new google.maps.Marker({
position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
map: map,
title: "My Location"
});
loadMarkers();
});
$scope.map = map;
});
function loadMarkers(){
//Get all of the markers from our Markers factory
Markers.getMarkers().then(function(markers){
console.log("Markers: ", markers);
var records = markers.data.markers;
console.log(records.length);
for (var i = 0; i < records.length; i++) {
var record = records[i];
var markerPos = new google.maps.LatLng(record.latitude, record.longitude);
console.log(record.latitude);
// Add the markerto the map
var marker = new google.maps.Marker({
setMap: map,
animation: google.maps.Animation.DROP,
position: markerPos
});
var infoWindowContent = "<h4>" + record.name + "</h4>";
addInfoWindow(marker, infoWindowContent, record);
}
});
}
function addInfoWindow(marker, message, record) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
})
this is the result, the marker which get latitude and longitude from database doesn't show up
Okay I have seen the mistake, when you create the marker in your loadMarkers() function you have this:
var marker = new google.maps.Marker({
setMap: map,
animation: google.maps.Animation.DROP,
position: markerPos
});
You are using as key setMap and it's map, so the code should be:
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: markerPos
});

Incorrect marker location

I am Using the $http Service in Ionic to dynamically load Google Map Markers, and I use this method:
google.maps.Geocode
To give a lat and lang, but this code is throwing some error.
facebookExample.controller('carteController', function ($scope, $ionicLoading, $location, $cordovaGeolocation, $compile, $http) {
$scope.back = function () {
$location.path("/accueil");
}
$scope.init = function () {
$http.get('http://#ip:8080/elodieService/categories/', {
params: {
fields: "nomcategorie,typecategorie",
format: "json"
}
}).then(function (result) {
console.log("SUCCESS!" + result.data);
console.log(JSON.stringify(result));
$scope.categorieData = result.data;
});
var options = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(options).then(function (position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListenerOnce($scope.map, 'idle', function () {
var marker = new google.maps.Marker({
map: $scope.map,
animation: google.maps.Animation.DROP,
position: latLng
});
$http.get('http://#ip/elodieService/evenements/', {
params: {
fields: "adresse",
format: "json"
}
}).then(function (result) {
console.log("SUCCESS!" + result.data);
console.log(JSON.stringify(result));
$scope.adresseData = result.data;
console.log("result.data: ", result.data.adresse);
var records = result.data;
for (var i = 0; i < records.length; i++) {
var record = records[i];
var adresse = record.adresse;
console.log("adresse obtenu par web service");
console.log(adresse);
var resultat = "";
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': adresse}, callback);
function callback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log("results[0].geometry.location");
console.log(results[0].geometry.location.latitude);
lat = results[0].geometry.location.lat();
console.log("lat");
console.log(lat);
lng = results[0].geometry.location.lng();
console.log("lng");
console.log(lng);
console.log(JSON.stringify(results));
var markerPos = new google.maps.LatLng(lat[i], lng[i]);
var marker = new google.maps.Marker({
map: $scope.map,
animation: google.maps.Animation.DROP,
position: markerPos
});
} else {
console.log(status);
}
}
}
});
var infoWindow = new google.maps.InfoWindow({
content: "Here I am!"
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open($scope.map, marker);
});
console.log(status);
}, function (error) {
console.log("Could not get location");
});
});
}
});
carte.html
<ion-view title="Carte" ng-init="init()">
<ion-content>
<div id="map" data-tap-disabled="true"></div>
</ion-content>
</ion-view>
Error:
incorrect marker location
How can I fix it?
You are passing the incorrect value to LatLng class as lat[i], lng[i]. The index position [i] is invalid.
So change your code like this:
lat = results[0].geometry.location.lat();
console.log("lat");
console.log(lat);
lng = results[0].geometry.location.lng();
console.log("lng");
console.log(lng);
console.log(JSON.stringify(results));
var markerPos = new google.maps.LatLng(lat, lng); // << Fix it here
Even, you don't have to define those lat and lng because you are getting it from a LatLng instance.
if (status == google.maps.GeocoderStatus.OK) {
console.log("results[0].geometry.location", results[0].geometry.location, JSON.stringify(results));
// No need to initialize again as the "results[0].geometry.location" is an instance of LatLng class itself
var markerPos = results[0].geometry.location;
var marker = new google.maps.Marker({
map: $scope.map,
animation: google.maps.Animation.DROP,
position: markerPos
});
}
See Geocoding Results:
results[]: {
types[]: string,
formatted_address: string,
address_components[]: {
short_name: string,
long_name: string,
postcode_localities[]: string,
types[]: string
},
partial_match: boolean,
place_id: string,
postcode_localities[]: string,
geometry: {
location: LatLng,
location_type: GeocoderLocationType
viewport: LatLngBounds,
bounds: LatLngBounds
}
}

Markers click events are not working in mobile device

I have created google maps for Nearby food courts. In this markers are displayed in browser and clickable and giving info window data.But same thing coming to mobile, markers are displayed and when am clicking the marker(tap the marker) info window data is not displayed.I tried with so many forums and changes lot of code and debug but i couldn't find the solution.
foodFactory.js
var foodModule = angular.module('foodModule', []);
foodModule.factory("foodFactory", ['$rootScope', '$window','foodServices', 'localStorageService', '$state', '$ionicLoading','$stateParams',
function($rootScope, $window, foodServices, localStorageService, $state, $ionicLoading, $stateParams, $cordovaGeolocation ) {
var foodCourtmap = {};
var marker = {};
var directionsDisplay = new google.maps.DirectionsRenderer({'draggable': true });
var directionsService = new google.maps.DirectionsService();
foodCourtmap.centerOnMe = function() {
initialize();
};
//intialze the google map it's show current location.
function initialize() {
var infowindow = new google.maps.InfoWindow();
navigator.geolocation.getCurrentPosition(function(pos) {
foodCourtmap.latitude = pos.coords.latitude;
foodCourtmap.longitude = pos.coords.longitude;
var site = new google.maps.LatLng( foodCourtmap.latitude, foodCourtmap.longitude);
var currentmapOptions = {
center: site,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//current location address based on Latitude and Longitude
var lat = parseFloat(foodCourtmap.latitude);
var lng = parseFloat(foodCourtmap.longitude);
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var contentString = "Location: " + results[1].formatted_address;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Current Location'
});
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
}
});
var map = new google.maps.Map(document.getElementById("food_map_canvas"), currentmapOptions);
// Places
var request = {
location:site,
radius: '5000',
name: ['restaurent']
};
var service = new google.maps.places.PlacesService(map);
service.search( request, callback );
function callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
else
{
alert('No results found');
}
}
var image = new google.maps.MarkerImage('img/Restaurant.png');
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
title: place.name+","+place.vicinity,
position: place.geometry.location,
icon:image
});
var contentString = place.name+","+place.vicinity;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
foodCourtmap.map = map;
});
};
$rootScope.createFoodCourt = function() {
foodCourtmap.centerOnMe();
}
return {
init: function() {
foodCourtmap.centerOnMe();
return foodCourtmap;
}
};
}
]);
food.html
<ion-view>
<ion-content scroll="false">
<div id="food_map_canvas" data-tap-disabled="true" style="float:right;width:100%; height:100%"></div>
</ion-content>
</ion-view>
So please anyone help in these regards.
The mousedown event was an improvement, however, on iOS the events still fired intermittently for me. After more investigation I found a solution that works 100% of the time by setting optimized: false when creating the marker in addition to using the mousedown event.
E.g.
var newMarker = new google.maps.Marker({
position: latLong,
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/green-dot.png',
optimized: false
});
https://code.google.com/p/gmaps-api-issues/issues/detail?id=3834
I had the same issue. The problem was 'click' event is not triggering when we touch on the mobile screen. So I changed to 'mousedown' event. Now I am able to add markers

Resources