Put markers in Google maps using Angular Maps - angularjs

var app = angular.module('myapp', ['ngMap']);
app.controller('PolygonArraysCtrl', function (NgMap) {
var myCenter;
var vm = this;
var latlong = [];
var infoWindow = new google.maps.InfoWindow();
NgMap.getMap().then(function (map) {
vm.map = map;
});
vm.showArrays = function (event) {
vm.method1 = function () { alert("shaishav") };
latlong = new Array;
$("#label_CoOrdinates").html("");
// Since this polygon has only one path, we can call getPath()
// to return the MVCArray of LatLngs.
var vertices = this.getPath();
var contentString = '<b>Bermuda Triangle polygon</b><br>' +
'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
'<br>';
// Iterate over the vertices.
for (var i = 0; i < vertices.getLength() ; i++) {
var xy = vertices.getAt(i);
contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
xy.lng();
latlong.push(xy.lat() + "_" + xy.lng());
}
$("#label_CoOrdinates").text(latlong);
$.ajax({
type: "POST",
dataType: "json",
url: "/Home/Index",
data: { position: $("#label_CoOrdinates").text() },
success: function (Data) {
var mydata = Data;
$.each(mydata.data, function (index, element) {
/*Add Marker to th map*/
myCenter = new google.maps.LatLng(mydata.data[index].Latitude, mydata.data[index].Longitude);
vm.postition = myCenter;
alert(vm.postition);
/*Push marker element into markers array*/
vm.positions = myCenter;
var marker = new google.maps.Marker({
position: myCenter,
map: map,
title: 'Hello World!'
});
});
},
error: function () {
alert('Error - ');
}
});
// Replace the info window's content and position.
//infoWindow.setContent(contentString);
//infoWindow.setPosition(event.latLng);
infoWindow.open(vm.map);
}
});
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maps.google.com/maps/api/js?libraries=placeses,visualization,drawing,geometry,places"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<script src="~/Scripts/app.js"></script>
</head>
<body>
<div ng-controller="PolygonArraysCtrl as vm">
<label id="label_CoOrdinates" style="display:none"></label>
<ng-map zoom="12" center="38.681659, -121.351705" map-type-id="TERRAIN">
<shape name="polygon" on-click="vm.showArrays()" paths="[ [38.681659, -121.351705], [38.535092, -121.481367], [38.621188 , -121.270555]]"
stroke-color="#FF0000"
stroke-opacity="0.8"
stroke-weight="2"
fill-color="#FF0000"
fill-opacity="0.35"
editable="true"
draggable="true">
</shape>
<marker ng-repeat="p in vm.positions" position="{{p}} "></marker>
</ng-map>
<input type="submit" ng-click=" vm.showArrays.method1()" value="Submit" />
</div>
</body>
</html>
Here is my app.js in that i am getting lat and long for markers but i dont know how to put them on the maps.And it's in for each loop so i need all markers that comes..also when i drag my polygon and click into it previous markers will remove and new markers appear.

In AngularJS you don't need jQuery and $.ajax to do an HTTP request (GET or POST), you can easily use $http service.
Then having received your data from backend service you can assign them to a $scope properties and bind a in a ngRepeat loop.
So in HTML do this:
<ng-map center="{{cx.latitude}}, {{cx.longitude}}" zoom="7">
<marker ng-repeat="p in places track by $index" position="{{p.lat}}, {{p.lng}}"></marker>
</ng-map>
In JS controller:
app.controller('mapCtrl', function(NgMap, $scope, $http) {
var url = "places.json";
$http({
method: 'GET',
url: url
}).then(function(response) {
// success
console.log(response);
$scope.cx = response.data.cx;
$scope.places = response.data.places;
NgMap.getMap().then(function(map) {
var cx = map.getCenter();
var txt = "center is: lat=" + cx.lat() + ", lng=" + cx.lng();
console.log(txt);
});
}, function(err) {
// error
});
});
See this working example: http://plnkr.co/edit/KUCMVdgRZ3TsN9P0FlZR?p=preview

Related

express-angular-node: Voting Application

the following are my two files for a simple voting app and for some reason the button are not increasing the count only when you refresh the voting.html page does both count increase by one. Your help is appreciated.
<!-- voting.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Voting</title>
<script src="angular.min.js"></script>
<script>
var app = angular.module('myFirstApp', []);
app.controller('CounterCtrl', function($scope,$http) {
console.log('CounterCtrl started');
// $scope.countA = 0;
// $scope.countB = 0;
// $scope.Acrease = function() {
// console.log('Acrease() called');
// $scope.countA++;
// };
// $scope.Bcrease = function() {
// console.log('Bcrease() called');
// //if($scope.count>0) $scope.count--;$scope.count++;
// $scope.countB++;
// };
function getItemsA() {
$http.get('/voteA').then(function(res) {
$scope.countA = res.data;
//$scope.countA = res.json(A);
console.log('/voteA: ', $scope.countA);
});
}
getItemsA();
function getItemsB() {
$http.get('/voteB').then(function(res) {
$scope.countB = res.data;
//$scope.countA = res.json(A);
console.log('/voteB: ', $scope.countB);
});
}
getItemsB();
// $scope.addItem = function() {
// console.log('addItem()\t newItem=', $scope.newItem);
// $http.get('/list/add/' + $scope.newItem).then(getItems);
// };
});
</script>
</head>
<body ng-app="myFirstApp">
<div ng-controller="CounterCtrl">
<p>Count of A Vote: <b>{{countA}}</b></p>
<p>Count of B Vote: <b>{{countB}}</b></p>
<input type="button" ng-click="getItemsA()" value="A">
<input type="button" ng-click="getItemsB()" value="B">
</div>
</body>
</html>
/***server.js***/
var express = require('express');
var app = express();
app.listen(3001, function() {
console.log('Listening on 3001');
});
// Mount the public directory at /
app.use('/', express.static('./public'));
/********************************************
* This code is for voting.html
*******************************************/
// initialize the votes variables
var A = 0 ;
var B = 0 ;
// add the voteA
app.get('/voteA', function(req,res) {
//res.json(A);
A++
res.json(A);
});
// add the voteB
app.get('/voteB', function(req,res) {
//res.json(A);
B++
res.json(B);
});
This is angular1 I presume.
I think your problem is that your ng-click is calling a function which is not in scope. I believe you should create scope functions:
$scope.getItemsA = function() {
$http.get('/voteA').then(function(res) {
$scope.countA = res.data;
console.log('response recieved');
});
};
Hope it helps..

Using a factory to pass data from one controller to another controller in AngularJS

I'm trying to take in the longitude and latitude values (using the google maps API) from one controller, and sending it to another controller.
To do this, I'm using a factory. However, there seems to be a problem with either sending the information into the factory, or reading from it.
.factory('loc', function(){
var location = {};
return {
setProperty: function(latitude, longitude){
location.lat = latitude;
location.lng = longitude;
},
getProperty: function(){
return location;
}
};
});
The first controller (google maps)
.controller('MapCtrl', function($scope, $ionicLoading,loc) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(pos) {
loc.setProperty(pos.coords.latitude, pos.coords.longitude)
...
In the second controller, I have:
.controller('callCtrl', function($scope,$state,loc) {
$scope.updateTask = function(data) {
task.location_lng = loc.getProperty().lng;
task.location_lat = loc.getProperty().lat;
...
This Works:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,loc) {
loc.setProperty(10,20);
});
app.controller('SubCtrl', function($scope,loc) {
$scope.updateData = function(){
//this is the change
$scope.lat = loc.getProperty().lat;
$scope.lng = loc.getProperty().lng;
}
});
app.factory('loc', function() {
var location = {};
return {
setProperty: function(latitude, longitude) {
location.lat = latitude;
location.lng = longitude;
},
getProperty: function() {
return location;
}
};
});
Demo : http://plnkr.co/edit/aWEEEjGmsnwMMtAAUZKV?p=preview
See running code here... http://play.ionic.io/app/a24d56659129
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link href="https://code.ionicframework.com/1.0.0/css/ionic.min.css" rel="stylesheet">
<script src="https://code.ionicframework.com/1.0.0/js/ionic.bundle.js"></script>
</head>
<body ng-app="app">
<ion-pane ng-controller="MainCtrl">
<ion-header-bar class="bar-stable">
<h1 class="title">Awesome App</h1>
</ion-header-bar>
<ion-content class="padding">
<button class="button button-assertive" ng-click="setLocation()">Set Property</button><br/><br/>
<button class="button button-assertive" ng-click="getLocation()">Get Property</button><br/><br/>
<button class="button button-assertive" ng-click="clearLocation()">Clear Property</button>
</ion-content>
</ion-pane>
</body>
</html>
app.js
var app = angular.module('app', ['ionic']);
app.controller('MainCtrl', function($scope,loc) {
//
$scope.setLocation = function() {
loc.setProperty( 100, 150)
}
$scope.getLocation = function() {
alert(JSON.stringify(loc.getProperty()));
}
$scope.clearLocation = function() {
loc.setProperty( "", "")
}
});
app.factory('loc', function() {
var location = {};
return {
setProperty: function(latitude, longitude){
location.lat = latitude;
location.lng = longitude;
},
getProperty: function(){
return location;
}
};
});
More complete example here http://play.ionic.io/app/f4332405a2c1

How to get AngularJS BLOB to Download PDF?

Hello everyone I am really new to developing with AngularJS and I am trying to figure out how to use BLOB to download a PDF locally to a machine. I already got it to work with a JSON and now I need a PDF. I have written some code but it doesn't seem to be working.
html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.center {
position: absolute;
left: 50%;
bottom: 50%;
}
.btn-purple {
background-color: rgb(97, 34, 115);
width: 100px;
}
</style>
<meta charset="UTF-8">
<title></title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="center" ng-controller="jsonController" ng-app="app">
<a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
<button type="button" class="btn btn-purple">{{fileName}}</button>
</a>
</div>
<div class="center" ng-controller="pdfController" ng-app="app">
<a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
<button type="button" class="btn btn-purple">{{fileName}}</button>
</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/javascript-canvas-to-blob/3.1.0/js/canvas-to-blob.js"></script>
<script src="app.js"></script>
</body>
</html>
controller.js
var app = angular.module('app', []);
app.config(['$compileProvider', function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);
}]);
app.controller('jsonController', function ($scope, $window, $http, $log) {
$http.get('data.json')
.success(function (info) {
var data = angular.toJson(info, true);
data = data.replace(/\n/g, "\r\n")
console.log(data)
var blob = new Blob([data], {type: "octet/stream"}),
url = $window.URL || $window.webkitURL;
$scope.fileUrl = url.createObjectURL(blob);
$scope.schemaName = "test"
$scope.fileName = $scope.schemaName + ".json"
})
});
app.controller("pdfController", function ($scope, $http, $log, $sce) {
$http.get('data.json' + $stateParams.id,
{responseType: 'arraybuffer'})
.success(function (response) {
var file = new Blob([(response)], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
});
Possible Try-
HTML:
<button ng-click="downloadPdf()" >Download PDF</button>
JS controller:
'use strict';
var app = angular.module('app')
.controller('ctrl', function ($scope, MathServicePDF) {
$scope.downloadPdf = function () {
var fileName = "file_name.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
ServicePDF.downloadPdf().then(function (result) {
var file = new Blob([result.data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
};
});
JS services:
app.factory('ServicePDF', function ($http) {
return {
downloadPdf: function () {
return $http.get('api/my-pdf', { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
};
});
Happy Helping!
Tested with large files (> 1.5 GB) on
Firefox 56.0
Safari 11.0
Use the following in your angular controller:
$scope.download = function() {
$http({
method: 'GET',
url: fileResourceUrl,
responseType: 'blob'
}).then(function(response) {
var blob = response.data;
startBlobDownload(blob, "largedoc.pdf")
});
};
function startBlobDownload(dataBlob, suggestedFileName) {
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
// for IE
window.navigator.msSaveOrOpenBlob(dataBlob, suggestedFileName);
} else {
// for Non-IE (chrome, firefox etc.)
var urlObject = URL.createObjectURL(dataBlob);
var downloadLink = angular.element('<a>Download</a>');
downloadLink.css('display','none');
downloadLink.attr('href', urlObject);
downloadLink.attr('download', suggestedFileName);
angular.element(document.body).append(downloadLink);
downloadLink[0].click();
// cleanup
downloadLink.remove();
URL.revokeObjectURL(urlObject);
}
}
Change your responseType from responseType: 'arraybuffer'
to responseType: 'blob'
In you controller PHP
return $pdf->stream();
In you controller AngularJS
$http.post('generate', {
dateStart: $scope.ds,
dateEnd: $scope.de
},
{
responseType: 'arraybuffer'
}).then(function success(response) {
var blob = new Blob([response.data], { type: "application/pdf"});
saveAs(blob, "filename.pdf");
}, function error(error) {
$scope.recordErrors(error);
});
This code worked for me in angular 9, Yii2, while using mpdf
this._gService.download_post(`controller/action`, postData).pipe(takeUntil(this._unsubscribeAll)).subscribe(result => {
const fileURL = URL.createObjectURL(result);
// Direct print preview
// const iframe = document.createElement('iframe');
// iframe.style.display = 'none';
// iframe.src = fileURL;
// document.body.appendChild(iframe);
// iframe.contentWindow.print();
// Direct Download
const fileName = 'Patient Report';
const a = document.createElement('a');
document.body.appendChild(a);
a.href = fileURL;
a.download = fileName;
a.click();
}, error => {
// show error message
});

Ionic/AngularJS & Wordpress API

I'm somewhat new to the JS world, so I'm struggling a bit as to what I did wrong. My sample data from wordpress API is not working. Any ideas what I did wrong:
app.controller('FeedCtrl', function($http, $scope, $ionicLoading) {
console.log("Loading FeedCtrl");
$scope.stories = [];
function loadStories(params, callback) {
$http.get('http://public-api.wordpress.com/rest/v1/freshly-pressed/', {params: params})
.success(function(response) {
var stories = [];
angular.forEach(response.data.children, function(child) {
stories.push(child.data);
});
callback(stories);
});
}
$scope.loadOlderStories = function() {
var params = {};
if ($scope.stories.length > 0) {
params['after'] = $scope.stories[$scope.stories.length - 1].name;
}
loadStories(params, function(olderStories) {
$scope.stories = $scope.stories.concat(olderStories);
$scope.$broadcast('scroll.infiniteScrollComplete');
});
};
$scope.loadNewerStories = function() {
var params = {'before': $scope.stories[0].name};
loadStories(params, function(newerStories) {
$scope.stories = newerStories.concat($scope.stories);
$scope.$broadcast('scroll.refreshComplete');
});
};
I've made a simplified example with your data.
Click the 'Load more' button to retrieve some posts. You should see a list with the title and the author of a post.
EDIT: There appears to be some cross-domain request issues, that's why the 'Load stories' button won't work. Just try to reflect this code inside your controller, it should work.
var app = angular.module('myApp', []);
app.controller('feedCtrl', function ($scope, $http) {
$scope.stories = [];
$scope.loadStories = function loadStories() {
console.log('loading stories');
$http.get('http://public-api.wordpress.com/rest/v1/freshly-pressed/')
.then(function onSuccess(response) {
console.log(response);
$scope.stories = response.data.posts;
}, function onFailed(error) {
console.error('Error:', error)
});
}
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="feedCtrl">
<button data-ng-click="loadStories()">Load stories</button>
<ul>
<li data-ng-repeat="story in stories">Title: {{ story.title }} - {{ story.author.first_name }} {{ story.author.last_name }}</li>
</ul>
</div>
</body>
</html>
Normally we wouldn't handle $http calls in our angular.controller. This needs to be done in an angular.service.

I am not getting the value of latlong for my device number

I am getting that Marker Is not defined and $scope is not defined error.
I want the latlong value by passing deviceid from the table.
I am unable to call the wcf service by Angulrjs
For Below DeviceId I have the LatLong Value(13.0357695, 77.59702219999997) In My Table
Here Is my Script
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html ng-app="RESTClientModule">
<head>
<title>Google Map</title>
<meta http-equiv="Content-Type" content="text/html; CHARSET=iso-8859-1">
<!-- Bootstrap Core CSS -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<%-- <script src="http://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script src="http://localhost:65235/GmapService.svc/getmapdata"></script>--%>
<script type="text/javascript">
var app;
var req;
var markers;
(function () {
app = angular.module("RESTClientModule", []);
})();
app.controller("RESTClientController", function ($scope, RESTClientService) {
$scope.lat = "0";
$scope.lng = "0";
$scope.markers = [];
instance = this;
instance.scope = $scope;
$scope.gMapModel = { deviceID: '911314150053752' }
req = $scope.gMapModel;
var promiseGet = RESTClientService.get();
promiseGet.then(function (pl) {
var latlng = pl.data.LatLong;
// alert(latlng);
latlng = latlng.split(',');
$scope.lat = latlng[0];
$scope.lng = latlng[1];
},
function (errorPl) {
$log.error('failure loading Employee', errorPl);
});
});
app.service("RESTClientService", function ($http) {
//alert(req);
this.get = function (result) {
return $http.post("http://localhost:65235/GmapService.svc/getmapdata", { "deviceID": "911314150055310" });
};
});
markers = [
{ "title": 'Bangalore',
"lat": $scope.lat,
"lng": $scope.lng,
"description": 'Test'
}
];
</script>
<script type="text/javascript">
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
</script>
THIS IS MY HTML WHERE I WANT TO GET LATLONG??
</head>
<body ng-controller="RESTClientController">
<form id="form1" runat="server">
<div>
<div id="dvMap" style="width: 700px; height: 700px">
</div>
</div>
</form>
</body>
</html>
You need to invoke google.maps.Map from inside your controller instead of from window.onload.
HTML
<div ng-app="mapsApp" ng-controller="MapCtrl">
<div id="map"></div>
</div>
JS
angular.module('mapsApp', []).controller('MapCtrl', function ($scope) {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(40.0000, -98.0000),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'),
mapOptions);
});

Resources