Angular JS service sending coordinates to controller - javascript

My app needs to get a path ( list of latitude and longitudes )in order to display it on a map.
I created a basic controller that does all the api calls.
function mainController($scope, $http){
$http.get('/api/lastrun')
.success(function(data){
$scope.lastrun = data;
})
.error(function(data){
console.log('Error: ' + data);
});
}
lastrun has a path array that lets you access the each position.
I created a mapController using angular-leaf-directive
function mapController($scope, positionService){
angular.extend($scope, {
run: {
lat: 0.0,
lng: 0.0,
zoom: 4
},
path: {
p1: {
color: 'red',
weight: 2,
latlngs: [
{ lat: 51.50, lng: -0.082 }, //here is an example of lat and lng in this controller
{ lat: 48.83, lng: 2.37 },
{ lat: 0, lng: 7.723812 }
]
}
}
});
}
What I want to do seems pretty easy. I just want to put the array of positions I get while calling /api/lastrun into my mapController in latlngs.
I'm not completely familiar with Services in AngularJS, but I tried to built mine (positionService). However it didn't work.
Does anyone here know how I can proceed in order to create with my service an array containing a list of {lat : , lng: } and call it into my mapController ?

I would have done :
$scope.lastrun = [];
$http.get('/api/lastrun')
.success(function(data){
angular.forEach(data, function (value) {
$scope.lastrun.push({lat : value.lat, lng : value.lng});
});
}
})
and then :
path: {
p1: {
color: 'red',
weight: 2,
latlngs: $scope.lastrun
}
Hope this helps

I have finally found a solution. I use Adrien's solution in my service, not in my controller and then return the lastrunpos array to my mapController. Here's my code :
var selftracking = angular.module('selftracking',["leaflet-directive"])
selftracking.service('positionService', function($http){
var lastrunpos = [];
$http.get('/api/lastrun')
.success(function(data){
angular.forEach(data.path, function (value) {
lastrunpos.push({lat : value.latitude, lng : value.longitude});
});
});
return {
getPos : function() {
return lastrunpos;
}
}
});
function mainController($scope, $http){
//Get all the last activities in the front page
$http.get('/api/lastactivity')
.success(function(data){
$scope.lastactivity = data;
})
.error(function(data){
console.log('Error: '+ data);
});
$http.get('/api/lastrun')
.success(function(data){
$scope.lastrun = data;
})
.error(function(data){
console.log('Error: ' + data);
});
}
function mapController($scope, positionService){
angular.extend($scope, {
run: {
lat: 51.505,
lng: -0.09,
zoom: 4
},
path: {
p1: {
color: 'red',
weight: 8,
latlngs: positionService.getPos()
}
}
});
}

Related

Using google map in Vue / Laravel

Trying to implement google map into Vue component. But having a hard time. Actually, there is no error. But no map also :) Okay, what I tried so far down below.
In laravel blade I set my api.
<script async defer src="https://maps.googleapis.com/maps/api/js?key={{env('GOOGLE_MAPS_API')}}&callback=initMap"></script>
Then in Vue component;
data() {
return {
mapName: "map",
//some other codes
}
},
mounted() {
this.fetchEstates();
},
methods: {
fetchEstates(page = 1) {
axios.get('/ajax', {
params: {
page
}}).then((response) => {
// console.log(response);
this.estates = response.data.data;
//some other codes....
//some other codes....
},
computed: {
//some other functions in computed...
//
initMap: function(){
var options =
{
zoom : 6,
center : {
lat:34.652500,
lng:135.506302
}
};
var map = new google.maps.Map(document.getElementById(this.mapName), options);
var marker = new google.maps.Marker({
map: map,
icon: 'imgs/marker.png',
url: "/pages/estates.id",
label: {
text: this.estates.price,
color: "#fff",
},
position: {
lat: this.estates.lat,
lng: this.estates.lng
}
});
google.maps.event.addListener(marker, 'click', function () {
window.location.href = this.url;
});
}
<div id="map"></div>
and last marker url id bind is in controller like this,
public function details($id)
{
$estates = allestates::where('id', $id)->first();
return view('pages.details', compact('estates'));
}
Do I missing something in Vue js? Thank you!
From our discussion in the comments, I realise that your issue is because this.estates is still not defined when initMap() is executed. Remember that you are using an asynchronous operation (via axios) to populate this.estates, so it is undefined at runtime. What you can do is:
Keep the map initialisation logic in initMap()
Move all the Google Map marker creation until after the axios promise has been resolved. You can abstract all that into another method, e.g. insertMarkers()
Also, remember that you need to define estates in the app/component data, otherwise it will not be reactive.
Here is an example:
data() {
return {
mapName: "map",
// Create the estate object first, otherwise it will not be reactive
estates: {}
}
},
mounted() {
this.fetchEstates();
this.initMap();
},
methods: {
fetchEstates: function(page = 1) {
axios.get('/ajax', {
params: {
page
}}).then((response) => {
this.estates = response.data.data;
// Once estates have been populated, we can insert markers
this.insertMarkers();
//pagination and stuff...
});
},
// Iniitialize map without creating markers
initMap: function(){
var mapOptions =
{
zoom : 6,
center : {
lat:34.652500,
lng:135.506302
}
};
var map = new google.maps.Map(document.getElementById(this.mapName), mapOptions);
},
// Helper method to insert markers
insertMarkers: function() {
var marker = new google.maps.Marker({
map: map,
icon: 'imgs/marker.png',
url: "/pages/estates.id",
label: {
text: this.estates.price,
color: "#fff",
},
position: {
lat: this.estates.lat,
lng: this.estates.lng
}
});
google.maps.event.addListener(marker, 'click', function () {
window.location.href = this.url;
});
}
},
Update: It also turns out that you have not addressed the issue of the data structure of this.estates. It appears that you are receiving an array from your endpoint instead of objects, so this.estates will return an array, and of course this.estates.lat will be undefined.
If you want to iterate through the entire array, you will have to use this.estates.forEach() to go through each individual estates while adding the marker, i.e.:
data() {
return {
mapName: "map",
// Create the estate object first, otherwise it will not be reactive
estates: {}
}
},
mounted() {
this.fetchEstates();
this.initMap();
},
methods: {
fetchEstates: function(page = 1) {
axios.get('/ajax', {
params: {
page
}}).then((response) => {
this.estates = response.data.data;
// Once estates have been populated, we can insert markers
this.insertMarkers();
//pagination and stuff...
});
},
// Iniitialize map without creating markers
initMap: function(){
var mapOptions =
{
zoom : 6,
center : {
lat:34.652500,
lng:135.506302
}
};
var map = new google.maps.Map(document.getElementById(this.mapName), mapOptions);
},
// Helper method to insert markers
insertMarkers: function() {
// Iterate through each individual estate
// Each estate will create a new marker
this.estates.forEach(estate => {
var marker = new google.maps.Marker({
map: map,
icon: 'imgs/marker.png',
url: "/pages/estates.id",
label: {
text: estate.price,
color: "#fff",
},
position: {
lat: estate.lat,
lng: estate.lng
}
});
google.maps.event.addListener(marker, 'click', function () {
window.location.href = this.url;
});
});
}
},
From what I can see in the screenshot you posted, this.estates is an array of objects? If that's the case you need to iterate through the array using forEach
this.estates.forEach((estate, index) => {
console.log(estate.lat);
//handle each estate object here
});
or use the first item in the array like so this.estates[0].lat, if you're only interested in the first item.

Google Maps Marker Animation, with KnockoutJs

I'm currently working on a map project with the Google Maps API, and KnockoutJS. I've managed to get most of my framework up and going, but the last piece of functionality is dodging me.
I'm trying to make it so when you click one of the pre-loaded locations on the left navigation bar, that it triggers the Google Maps marker animation, just like clicking on the actual marker does, as well as when filtering the list.
Here's my code so far:
// Define all variables to satisfy strict mode.
var document;
var setTimeout;
var alert;
var ko;
var google;
// Parsing for dynamic background & quote.
function parseQuote(response) {
"use strict";
document.getElementById("quote").innerHTML = response.quoteText;
document.getElementById("author").innerHTML = "Author - <b>" + response.quoteAuthor + "</b>";
}
// Specify all locations on map.
function model() {
"use strict";
var locations = [{
title: "The Hub",
lat: 39.521975,
lng: -119.822078,
id: "The Hub"
}, {
title: "The Jungle",
lat: 39.524982,
lng: -119.815983,
id: "The Jungle"
}, {
title: "Bibo Coffee Company",
lat: 39.536966,
lng: -119.811042,
id: "Bibo Coffee Company"
}, {
title: "Purple Bean",
lat: 39.531135,
lng: -119.833802,
id: "Purple Bean"
}, {
title: "Sips Coffee and Tea",
lat: 39.530438,
lng: -119.814742,
id: "Sips Coffee and Tea"
}];
return locations;
}
var listLocations = ko.observableArray(model());
// Initalize map location & position.
function initMap() {
"use strict";
var map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: 39.529633,
lng: -119.813803
},
zoom: 14
});
// Define markers & content.
listLocations().forEach(function (data) {
var positionMk = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: positionMk,
map: map,
title: data.title,
animation: google.maps.Animation.DROP
});
var infowindow = new google.maps.InfoWindow({
content: data.title
});
data.mapMarker = marker;
marker.addListener("click", function () {
data.triggerMarker(marker);
listLocations().forEach(function (place) {
if (data.title === place.title) {
place.openInfoWindow();
} else {
place.closeInfoWindow();
}
});
});
map.addListener("click", function () {
listLocations().forEach(function (place) {
place.closeInfoWindow();
});
});
var setMk = function (marker) {
infowindow.open(map, marker);
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
marker.setAnimation(null);
}, 750);
};
data.triggerMarker = setMk.bind();
var openMk = function () {
infowindow.open(map, marker);
};
data.openInfoWindow = openMk.bind();
var closeMk = function () {
infowindow.close(map, marker);
};
data.closeInfoWindow = closeMk.bind();
});
}
// Define ViewModel for list and sorting of list.
function ViewModel() {
"use strict";
var self = {};
self.placeList = ko.observableArray([]);
listLocations().forEach(function (place) {
place.visible = ko.observable(true);
self.placeList.push(place);
});
self.filterValue = ko.observable("");
self.filterList = ko.computed(function () {
listLocations().forEach(function (place) {
var searchParam = self.filterValue().toLowerCase();
var toBeSearched = place.title.toLowerCase();
place.visible(toBeSearched.indexOf(searchParam) > -1);
if (place.mapMarker) {
place.mapMarker.setVisible(toBeSearched.indexOf(searchParam) > -1);
}
if (place.visible() && searchParam && place.mapMarker) {
place.triggerMarker(place.mapMarker);
} else if (place.mapMarker) {
place.closeInfoWindow();
}
});
});
// Responsiveness for clicking locations on the list.
self.onClickListener = function (data) {
listLocations().forEach(function (place) {
if (data.title === place.title) {
place.openInfoWindow();
} else {
place.closeInfoWindow();
}
});
};
return self;
}
ko.applyBindings(new ViewModel());
// Error handling for API's.
function forismaticError() {
"use strict";
alert("Forismatic API is unreachable, please check your internet connection and try again.");
}
function googleMapsError() {
"use strict";
alert("Google Maps API is unreachable, please check your internet connection and try again.");
}
Any insight that can be offered into this would be appreciated! I feel like it's obvious, but my tired brain is failing me.
In addition, here's a quick JSFiddle of the entire project as well.
You just needed to copy the line of code that triggers the animation to your self.onClickListener function:
self.onClickListener = function (data) {
listLocations().forEach(function (place) {
if (data.title === place.title) {
place.openInfoWindow();
place.triggerMarker(place.mapMarker);
} else {
place.closeInfoWindow();
}
});
};

Google Map Address Search With GPS Location

I try to do a map with seach address/find location and take gps coordinate/find location. I can make to work one by one but I couldn't work them together in one map. These are my google map functions :
Address Search
// When the search form is submitted
jQuery('.js-form-search').on('submit', function(){
GMaps.geocode({
address: jQuery('.js-search-address').val().trim(),
callback: function ($results, $status) {
if (($status === 'OK') && $results) {
var $latlng = $results[0].geometry.location;
$mapSearch.removeMarkers();
$mapSearch.addMarker({ lat: $latlng.lat(), lng: $latlng.lng(), title: 'Adres : '+jQuery('.js-search-address').val()});
$mapSearch.fitBounds($results[0].geometry.viewport);
document.getElementById("lat").value = $latlng.lat();
document.getElementById("long").value = $latlng.lng();
} else {
alert('Adres Bilgisi Bulunamadı ! ');
}
}
});
return false;
});
GPS Location finder
// When the GPS button clicked
jQuery('.js-form-gps').on('submit', function(){
GMaps.geolocate({
success: function(position) {
$mapSearch.setCenter(position.coords.latitude, position.coords.longitude);
$mapSearch.addMarker({
lat: position.coords.latitude,
lng: position.coords.longitude,
animation: google.maps.Animation.DROP,
title: 'GeoLocation',
infoWindow: {
content: '<div class="text-success"><i class="fa fa-map-marker"></i> <strong>Your location!</strong></div>'
}
});
},
error: function(error) {
alert('Geolocation failed: ' + error.message);
},
not_supported: function() {
alert("Your browser does not support geolocation");
},
always: function() {
// Message when geolocation succeed
}
});
return false;
});
};
How can I entegrate two of them ?
Thanks,

Angular-google-maps: How to show Title and Description dynamically on markers

I am using Angular-google-maps, HTML code follows
<ui-gmap-google-map center='mapData.map.center' zoom='mapData.map.zoom'
events="mapEvents">
<ui-gmap-markers models="mapData.map.markers" coords="'self'">
</ui-gmap-markers>
</ui-gmap-google-map>
in JS calling
angular.extend(this, $controller('MapsMixinController',
{$scope:$scope, map:mapData.data[0].map}));
MapsMixinController as follows. Calling this controller from js code. Markers are showing & on click able to mark.
MapsMixinController.js
/**
* Controller providing common behaviour for the other map controllers
*/
angular
.module('app')
.controller('MapsMixinController', ['$scope', 'GeolocationService', 'uiGmapGoogleMapApi', 'map',
function($scope, GeolocationService, GoogleMapApi, map) {
var _this = this;
$scope.mapEvents = {
click: function(mapModel, eventName, originalEventArgs) {
var e = originalEventArgs[0];
if (e.latLng) {
$scope.mapData.map.markers.push({
id: new Date().getTime(),
latitude: e.latLng.lat(),
longitude: e.latLng.lng()
});
// This event is outside angular boundary, hence we need to call $apply here
$scope.$apply();
}
}
};
// Returns a default map based on the position sent as parameter
this.getDefaultMap = function(position) {
return {
markers: [],
center: {
latitude: position.coords.latitude,
longitude: position.coords.longitude
},
zoom: 14
};
};
// Initialize the google maps api and configure the map
GoogleMapApi.then(function() {
GeolocationService().then(function(position) {
$scope.mapData.map = map || _this.getDefaultMap(position);
}, function() {
$scope.error = "Unable to set map data"; // TODO use translate
});
});
}
]);
How can I show title on mouse hover on markers? And on click how to show description on markers?
You can add title property alone with latitude and longtitude property while creating marker data.
/**
* Controller providing common behaviour for the other map controllers
*/
angular
.module('app')
.controller('MapsMixinController', ['$scope', 'GeolocationService', 'uiGmapGoogleMapApi', 'map',
function($scope, GeolocationService, GoogleMapApi, map) {
var _this = this;
$scope.mapEvents = {
click: function(mapModel, eventName, originalEventArgs) {
var e = originalEventArgs[0];
if (e.latLng) {
$scope.mapData.map.markers.push({
id: new Date().getTime(),
latitude: e.latLng.lat(),
longitude: e.latLng.lng(),
title: "Mouse over text"
});
// This event is outside angular boundary, hence we need to call $apply here
$scope.$apply();
}
}
};
// Returns a default map based on the position sent as parameter
this.getDefaultMap = function(position) {
return {
markers: [],
center: {
latitude: position.coords.latitude,
longitude: position.coords.longitude
},
zoom: 14
};
};
// Initialize the google maps api and configure the map
GoogleMapApi.then(function() {
GeolocationService().then(function(position) {
$scope.mapData.map = map || _this.getDefaultMap(position);
}, function() {
$scope.error = "Unable to set map data"; // TODO use translate
});
});
}
]);

Google Maps for Angular directive not working in function

I'm attempting to use this Google Maps for AngularJS directive inside another function. The code works when I move $scope.map outside the function call and set the lat/lon statically. However, what I want to do is set the lat/lon dynamically within my function call.
Code below.
html:
<google-map center="map.center" zoom="map.zoom"></google-map>
Angular controller:
angular.module('StadiumCtrl', []).controller('StadiumController', function($scope, $rootScope, $routeParams, $sce, Stadia, Instagram, Weather) {
// pull stadium details from API based on routeParams
$scope.id = $routeParams.id;
Stadia.get($scope.id).success(function(response) {
$rootScope.logo = response.logo;
$scope.homeColors = {
"border": "2px solid " + response.sec_hex,
"box-shadow": "3px 3px 7px " + response.prim_hex,
"margin": "6px",
"padding": "0"
}
$scope.map = {
center: {
latitude: response.loc[1],
longitude: response.loc[0]
},
zoom: 8
};
// pass loc_id into Instagram API call
Instagram.get(response.loc_id).success(function(response) {
instagramSuccess(response.loc_id, response);
});
// pass city and state into Wunderground API call
Weather.get(response.city, response.state).success(function(response) {
$rootScope.temp = Math.round(response.current_observation.temp_f);
});
// Instagram API callback
var instagramSuccess = function(scope,res) {
if (res.meta.code !== 200) {
scope.error = res.meta.error_type + ' | ' + res.meta.error_message;
return;
}
if (res.data.length > 0) {
$scope.items = res.data;
} else {
scope.error = "This location has returned no results";
}
};
});
It looks like the google-maps directive needs an initial value when the directive gets linked. Once there is a default value it will respond to changes in that scope value.
You can see this in action with the following code:
$scope.map = {center: {latitude:0,longitude:0}, zoom: 0};
$timeout(function() {
$scope.map = {center: {latitude: 51.219053, longitude: 4.404418 }, zoom: 14 };
}, 1000);
which is demonstrated at http://plnkr.co/edit/szhdpx2AFeDevnUQQVFe?p=preview. If you comment out the $scope.map assignment outside the $timeout the map will no longer show up, but if you put line 3 back it in will update the map when the $timeout executes.
In your case, you should simply be able to add
$scope.map = {
center: {
latitude: 0,
longitude: 0
},
zoom: 0
};
just before you run Stadia.get($scope.id).success(function(response) {.

Categories

Resources