Loading Google Places Autocomplete Async Angular 2 - asynchronous

I am trying to instantiate a Google Places Autocomplete input within an Angular 2 component. I use this code to do it:
loadGoogle() {
let autocomplete = new google.maps.places.Autocomplete((this.ref.nativeElement), { types: ['geocode'] });
let that = this
//add event listener to google autocomplete and capture address input
google.maps.event.addListener(autocomplete, 'place_changed', function() {
let place = autocomplete.getPlace();
that.place = place;
that.placesearch = jQuery('#pac-input').val();
});
autocomplete.addListener()
}
Normally, I believe, I would use the callback function provided by the Google API to ensure that it is loaded before this function runs, but I do not have access to it within a component's scope. I am able to load the autocomplete input 90% of the time, but on slower connections I sometimes error out with
google is not defined
Has anyone figured out how to ensure the Google API is loaded within a component before instantiating.

Not sure whether this will help, but I just use a simple script tag in my index.html to load Google API and I never get any error. I believe you do the same as well. I post my codes here, hope it helps.
Note: I use Webpack to load other scripts, except for Google Map API.
<html>
<head>
<base href="/">
<title>Let's Go Holiday</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Google Map -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<your-key>&libraries=places"></script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
And then in your component:
...
declare var google: any;
export class SearchBoxComponent implements OnInit {
ngOnInit() {
// Initialize the search box and autocomplete
let searchBox: any = document.getElementById('search-box');
let options = {
types: [
// return only geocoding results, rather than business results.
'geocode',
],
componentRestrictions: { country: 'my' }
};
var autocomplete = new google.maps.places.Autocomplete(searchBox, options);
// Add listener to the place changed event
autocomplete.addListener('place_changed', () => {
let place = autocomplete.getPlace();
let lat = place.geometry.location.lat();
let lng = place.geometry.location.lng();
let address = place.formatted_address;
this.placeChanged(lat, lng, address);
});
}
...
}

I used it the same way as explained above but as per google page speed i was getting this suggestion,
Remove render-blocking JavaScript:
http://maps.googleapis.com/…es=geometry,places&region=IN&language=en
So i changed my implementation,
<body>
<app-root></app-root>
<script src="http://maps.googleapis.com/maps/api/js?client=xxxxx2&libraries=geometry,places&region=IN&language=en" async></script>
</body>
/* Now in my component.ts */
triggerGoogleBasedFn(){
let _this = this;
let interval = setInterval(() => {
if(window['google']){
_this.getPlaces();
clearInterval(interval);
}
},300)
}
You can do one more thing, emit events once the value(google) is received,& trigger your google task
inside them.

Related

How to prevent Google AdWords script from prevent reloading in SPA?

I have a SPA built on React JS stack. I'm using react-router to navigate through pages and i need to implement Google AdWords on my website.
<script type="text/javascript">
/* <![CDATA[ */
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = 333333;
w.google_conversion_label = "33333";
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
var opt = new Object();
opt.onload_callback = function() {
if (typeof(url) != 'undefined') {
window.location = url;
}
}
var conv_handler = window['google_trackConversion'];
if (typeof(conv_handler) == 'function') {
conv_handler(opt);
}
}
/* ]]> */
</script>
I embed this code in body and i run goog_report_conversion when i click on button which navigates me to another page. Which is unwanted behaviour for SPA.
<Link
className="btn btn-primary"
to="/settings"
onClick={() => goog_report_conversion('site.name/settings')}
>Go to settings</Link>
The problem is that once I do it, it fully reloads my webpage.
I know that this line causes the problem
window.location = url;
But without it script doesn't work.
I also tried to create this event in Google Tag Manager and follow advices given here Google Tag Manager causes full page reload in SPA - React but it didn't help me.
Have anyone faced same problem implementing AdWords in SPA? How did you solve it?
I feel that the implementation example for the asynchronous Remarketing/Conversion snippet is needlessly complex. Here's something that we used in a similar scenario.
First we define a little helper function that we can reuse:
<script type="text/javascript">
function triggerConversion(conversionID, conversionLabel) {
if (typeof(window.google_trackConversion) === "function") {
window.google_trackConversion({
google_conversion_id: conversionID,
google_conversion_label: conversionLabel,
google_remarketing_only: false
});
}
}
</script>
then we include Google's async conversion script (ideally somewhere where it doesn't block rendering):
<script type="text/javascript"
src="http://www.googleadservices.com/pagead/conversion_async.js"
charset="utf-8">
</script>
And now you can track conversions on any element, like so, to adapt your example:
<Link
className="btn btn-primary"
onClick={() => triggerConversion(333333, "33333")}
>Go to settings</Link>

How to dynamically create properties in polymer as needed

I have a use case where I have a component (like a database) that I would like to expose all the information as bindable properties. However, only a few of those properties will be need by any particular client who uses it. There could be 1000's of entries in the database. How can I figure out which ones are actually needed by the client.
For example:
Polymer('database,
{
observer : {
name : function(oldVal, newVal) { onDataChanged('name', newVal);},
addr : function(oldVal, newVal) { onDataChanged('addr', newVal);},
tel.main : function(oldVal, newVal) { onDataChanged('tel.main',
etc....
}
});
In this case I would like to dynamically create observe handlers only for the data bindings that are actually needed on the fly.
If you are willing to have your clients extend your component to specify the desired database fields then you can dynamically create observers only for the fields they specify.
Example
Component
<link rel="import" href="../../webcomponents/bower_components/polymer/polymer.html">
<polymer-element name=demo-dynamicproperties >
<template>
<h2>dynamic properties</h2>
See the console for changes
</template>
<script>
Polymer({
// Validate that it is an attribute that is allowed
// For the example we will allow anything starting with validitem
isValidAttribute: function(name) {
return (name.match('^validitem'));
},
// Get attributes
created: function() {
for (name in this.publish) {
console.log("Trying: "+name);
// Verify that it is one of the dynamic attributes
if (this.isValidAttribute(name)) {
console.log("Accepting: "+name);
this[name]="Pull from DB";
// References:
// https://www.polymer-project.org/0.5/docs/polymer/node_bind.html
// https://github.com/Polymer/NodeBind/blob/master/tests/tests.js
// https://github.com/polymer/observe-js
var observer = new PathObserver(this,name);
observer.open(makeHandler(this,name));
}
}
/************* TEST **********************************/
// Verify that dynamic updates worked by updating
this.job('update_validitem1', function() {
this.validitem1="Updated after 10 seconds";
}, 10000);
/************ End Test ******************************/
}
});
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
function makeHandler(element, property) {
function handler(newval,oldval) {
console.log("element" + element,"property:" + property,"from:"+oldval,"to:"+newval);
}
return handler;
}
</script>
</polymer-element>
Usage
<!DOCTYPE HTML>
<html lang="en">
<head>
<script src="../../webcomponents/bower_components/webcomponentsjs/webcomponents.min.js"></script>
<link rel="import" href="../../webcomponents/bower_components/polymer/polymer.html">
<link rel="import" href="demo-dynamicproperties.html">
<title>demo-dynamicproperties test page</title>
</head>
<body>
<polymer-element name=demo-usedb extends="demo-dynamicproperties" attributes="validitem1 validitem2 invaliditem" noscript>
</polymer-element>
<h1>Demo</h1>
<template is="auto-binding">
<h2>Dynamic tag</h2>
<demo-usedb validitem1="{{item1choice2}}" item2="setthis"></demo-usedb>
<h2>Input</h2>
<input type="text" value="{{item1choice2}}">
<h3>Produces</h3>
{{item1choice2}}
</template>
</body>
</html>
It looks like the answer to the questions is that it cannot be done. There does not appear to be any hooks or events that a component can use to get notified when properties are bound (or attempted to be bound) to it. I filed a bug/enhancement request here
https://github.com/Polymer/polymer/issues/1303
to request that this feature be supported in the future.

Unknown provider when setting up Jasmine AngularJS service test

I have an angularjs service which calculates a products price based on discounts, quantity, etc. I'm trying to write a jasmine test to call this service, passing in test data. I get an error that the app is missing it's dependencies. I don't want to have to load Ui router, shouldn't mocks take care of that?
Error: [$injector:nomod] Module 'ui.router' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Here is my Jasmine SpecRunner.html. The Web project I am testing is in a different project than my Jasmine test project.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Jasmine Spec Runner v2.0.0</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.0/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.0/jasmine.css">
<script type="text/javascript" src="lib/jasmine-2.0.0/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-2.0.0/jasmine-html.js"></script>
<script type="text/javascript" src="lib/jasmine-2.0.0/boot.js"></script>
<script src="http://localhost:54411/Scripts/vendor/angular.js"></script>
<script src="http://localhost:54411/Scripts/vendor/angular-mocks.js"></script>
<script src="http://localhost:54411/Scripts/app.js"></script>
<!-- include source files here... -->
<script src="http://localhost:54411/Scripts/services/productPriceCalculatorSvc.js"></script>
<!-- include spec files here... -->
<script src="spec/ProductPriceCalculatorSpec.js"></script>
</head>
<body>
</body>
</html>
The spec file:
describe("Product Price Calculator service test", function () {
describe("when I call product price calculator.calculateCustomerDiscPrice", function () {
var sut;
beforeEach(function() {
module('quoteMasterApp');
inject(function(productPriceCalculatorSvc) {
sut = productPriceCalculatorSvc;
});
});
it('can calculate customer discount price', function() {
productPriceCalculatorSvc.calculateCustomerDiscPrice(null, null);
});
});
});
Here is my service declaration.
myApp.service("productPriceCalculatorSvc", [
function() {
return {
calculateCustomerDiscPrice: function(product, conversionRate) {
// calculations occur here
});
}
}
}
])
You need to tell the framework how to find your service.
Something like:
describe("ProductPriceCalculator", function () {
var productPriceCalculatorSvc;
beforeEach(function() {
module('productPriceCalculatorSvcFactory');
});
beforeEach(inject(function ($injector) {
productPriceCalculatorSvc = $injector.get('productPriceCalculatorSvcFactory');
}));
it('can calculate customer discount price', function () {
productPriceCalculatorSvc.calculateCustomerDiscPrice();
});
});
See more here: https://docs.angularjs.org/api/auto/service/$injector
I have the same case : test a controller that calls a service.
Here is what I have in my decribe
describe('Controller Test', function () {
var scope, ctrl;
// load your controllers including myController
beforeEach(module('mycontrollers'));
// load your services (do not forget to include them in your spec runner !)
// there should be myService defined in this module
beforeEach(module('myservices'));
// It seems a good practice to inject nothing in "it"
// Everything is injected in beforeEach
// here the controller uses theService and set some value in the scope
beforeEach(inject(function($rootScope, $controller, ReportProductService) {
scope = $rootScope.$new();
ctrl = $controller('myController', {
$scope: scope,
theService : myService
});
}));
it('should work', function () {
//verify that the controller is there
expect(ctrl).toBeDefined();
// do test
expect(scope.someExpectedValueSetByController).toBeDefined();
});
I can do a JSFiddle if you want
I can also make a better answer as my service is using $http
Please comment if you don't agree or find a better way to do it

Using the Facebook API after JavaScript Login

This is something I have been trying to figure out, but I am not sure exactly how to do it. I have a flex application that logs into facebook, but after that I can't access any of the facebook api. Right now I am using this HTML to log in:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<!-- Include support librarys first -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
//This example uses the javascript sdk to login before embedding the swf
var APP_ID = "[My App ID Here]";
var REDIRECT_URI = "http://apps.facebook.com/isotesthoskins/";
var PERMS = "publish_stream,offline_access"; //comma separated list of extended permissions
function init() {
FB.init({appId:APP_ID, status: true, cookie: true});
FB.getLoginStatus(handleLoginStatus);
}
function handleLoginStatus(response) {
if (response.session) { //Show the SWF
//A 'name' attribute with the same value as the 'id' is REQUIRED for Chrome/Mozilla browsers
swfobject.embedSWF("isotest.swf", "flashContent", "760", "500", "9.0", null, null, null, {name:"flashContent"});
} else { //ask the user to login
var params = window.location.toString().slice(window.location.toString().indexOf('?'));
top.location = 'https://graph.facebook.com/oauth/authorize?client_id='+APP_ID+'&scope='+PERMS+'&redirect_uri='+REDIRECT_URI+params;
}
}
$(init);
</script>
And everything logs in fine, but when I try this in the application after I am logged in, nothing happens.
Facebook.api("/me", function(response){
changeText.text = response.name;
});
I don't need to init because it was done by the javascript login, right? I might be wrong about that though.
Looks like you are calling the API using the Flex SDK.
That is not going to work, as the token is not shared between JS and Flex.
You should login on the Flex side or thunk into the JS to make the call.

How to use own map database to show a map on website?

How to use own map database to display map on a website and use that map to find route and do other stuff ?
You should try the Google Maps API. http://code.google.com/apis/maps/index.html
You can store locations or routes in your database and use the Maps API to display them. Not sure if this is what you're looking for, but I've found their API really easy to use.
That is an absolutely massive task, I'm not sure I understand your question correctly... You've tagged this with Javascript, Web-development and map - so presumably you want to know how to implement a front-end that renders a map to a web page, and then performs custom pathfinding and other logic. Surely I'm misunderstanding you! :D
The O'rielly RESTful Web Services book uses a map service as its operative example throughout the book, so you may find it useful, at least for the design of your service front end. It doesn't delve into the implementation very deeply, particularly the actual mechanics of map image generation, as it is primarily concerned with the design of the service interface from an HTTP perspective. It also doesn't treat very much with the client-side logic that would be involved in dragging, zooming and the like.
You have two options in order to calculate routes depending on your database.
If your database has clean and accurate address names then you can easily use the google maps API that can be found here: https://developers.google.com/maps/documentation/directions/.
Bare in mind that you can only execute 2500 requests per day with the free version.
On the other hand if you have a network defined on your db (have the roads in a nodes and arcs manner) then you can implement Dijsktra's algorithm.
Have a look here: http://www.vogella.com/articles/JavaAlgorithmsDijkstra/article.html
Because of the fact that the network should be loaded from the database in order to calculate the best route I suggest the singleton pattern.
An OpenSource way to do this, which I would recommend in most cases, is using GeoServer and OpenLayers.
GeoServer can read gegraphic data from all the major databases and be used as host for the widely used standard GeographicgWebServices WMS and WFS.
OpenLayers is a JavaScript API to show your map on the webpage.
I recently implemented something like this. I realize it is an old question but Google has the javascript api v3 out for Google Maps and it works great.
https://developers.google.com/maps/articles/phpsqlajax_v3
This page helped me implement the entire system. Works great. You can also use php to update and edit the entries on the map.
You need xml pages and others but here is the map html page just to give you an idea of the javascript it entails.
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>

Resources