This question already has answers here:
Angular Js and google api client.js (gapi)
(8 answers)
Closed 6 years ago.
I am really new to Angular. I am trying to execute my code defined in a controller in my app.js file. I need to do that by a javascript.
How to do that?
app.js file
app.controller('MyLocCtrl',function($firebaseObject){
myfunction = function () {
const rootRef = firebase.database().ref();
this.object = $firebaseObject(rootRef);
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'),{
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
};
}
);
and my JS code in another page//map.html
<script src="app.js"></script>
<body ng-app="app">
<div id="map" ng-app='app' ng-controller="MyLocCtrl"></div>
</body>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDUX6F83LCTZ7_uQlXzR6_Q2u6BXFIvGkY&callback=angular.element(document.getElementById('map')).firebaseObject().myfunction();">
</script>
</html>
You should have the app declared as an angular module like this:
var app = angular.module('myApp',[]);
app.controller('MyLocCtrl', ['$scope', function($scope) {
//
}]);
After that you are able to communicate with the html
Also, you already declared ng-app='app' in the body, you should remove it from the div element
Related
This question already has answers here:
Pass parameters to a url callback function in JavaScript
(3 answers)
Call function initmap with parameters in gmaps api
(2 answers)
Closed 6 months ago.
I am using the example from this document as reference. https://developers.google.com/maps/documentation/javascript/examples/layer-traffic
Basically, I have a html file and an external js file.
<!DOCTYPE html>
<html>
<head>
<title>Transit Layer</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap(51.501904,-0.115871)&v=weekly"
></script>
</body>
</html>
External js script:
function initMap(lat, lon) {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 13,
center: { lat: lat, lng: lon },
});
const transitLayer = new google.maps.TransitLayer();
transitLayer.setMap(map);
}
window.initMap = initMap;
How do I pass arguments initMap(51.501904,-0.115871) to the js function from html? I tried this in jsfiddle and it didn't work.
So I feel I'm almost there to the solution but I'm really in need of help here. What I'm trying to do is to create an array using .getValues() to get a range that contains four columns (Name, Address, Latitude, and Longitude). After that I want to return the variable back into a global variable and then call that variable from the HTML side. I tried linking the google script with the HTML and then calling the variable there but having quite a bit of trouble with that. Thank you guys for all of your help!
Below is the google script:
var id = 'Spreadsheet Key';
function doGet(e) {
var html = HtmlService.createTemplateFromFile('Sample');
return html.evaluate().setTitle('Directory Map');
}
function entries() {
var blop =
SpreadsheetApp.openById(id).getSheetByName('Sheet1').getRange('A1:D').getValues();
return blop;
}
This is the HTML in Google Script.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.8283, lng: -98.5795},
zoom: 5,
mapTypeId: 'roadmap',
gestureHandling: 'greedy'
});
var locations = [blop];
for (var i = 0; i < locations.length; i++) {
var sites = locations[i];
var myLatLng = new google.maps.LatLng(sites[2],sites[3]);
var sites = new google.maps.Marker({
position: myLatLng,
map: map,
title: sites[0],
});
};
}
</script>
<script> google.script.run.entries(); </script>
<script src="https://maps.googleapis.com/maps/api/js?key=MyAPIKey&libraries=places&callback=initAutocomplete"async defer></script>
<script src="https://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="SampleCode.gs"></script>
</body>
</html>
The starting point is:
<script> google.script.run.entries(); </script>
The above code runs when the page is loaded in the browser. You need a "success handler", and then the success handler can store the data somewhere. You could put the data into a window variable, or local browser storage.
<script>
window.storeSheetValues = function(theReturnedData) {
console.log('theReturnedData: ' + theReturnedData)
console.log('typeof theReturnedData: ' + typeof theReturnedData)
window.mySheetData = theReturnedData;//Put the data into a window variable
}
google.script.run
.withSuccessHandler(storeSheetValues)
.entries();
</script>
Check the data type of the return value coming back from the server. If it's a string, you may want to turn it back into an array.
I am trying to add google maps to a component that is using sightly. The component will let users select an asset and then grab the lat/long from the assets properties and then show the location with a marker in google map.
my googlemap.html page contains the following at the moment.
<div data-sly-use.ev="Google"
class="${ev.cssClass || ''}"
title="${ev.title || ''}"
data-emptytext="Evernote Asset"
id="${ev.googleClass || ''}"
>
</div>
<style>
#map-canvas {
width: 500px;
height: 400px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
center: myLatlng,
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions)
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
My Google.java is like this
public class Google extends WCMUse {
public void activate () {
//grab the lat/long properties for the asset
}
public String googleClass() {
if (lat != null && long != null)
return "map-canvas";
else
return "";
}
public String getLat() {return lat;}
public String getLng() {return lng:]
}
Question
As you can see I have hardcoded the lat/long. How can I get the lat/long from my java class using the getters instead of hardcoding?
I tried the following but it doesn't work.
<div data-sly-use.ev="GoogleMap"
class="${ev.cssClass || ''}"
title="${ev.title || ''}"
data-emptytext="Evernote Asset"
id="${ev.googleClass || ''}"
>
<style>
#map-canvas {
width: 500px;
height: 400px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var myLatlng = new google.maps.LatLng("${ev.lat || ''}","${ev.lng || ''}");
var mapOptions = {
center: myLatlng,
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions)
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</div>
Sightly has XSS protection out the box. So in order to evaluate the expressions, the context should be used.
${ev.lat # context="scriptString"}
Your Javascript runs client side in the browser so will not normally interact with your Java code running server side. You might want to expose your Java method as a RESTful API endpoint and perform an AJAX call in the Javascript code.
SEE: http://docs.jquery.com/Tutorials (ajax tutorial)
Other ways are creating object on server side and expose that object from session or from some static functions and then you can use JSP servlet syntax to access that object.
<LI>Curent time: <%= new java.util.Date() %>
<LI>Host name: <%= request.getRemoteHost() %>
<LI>ID sesion: <%= session.getId() %>
</UL>
<% deleteconfig deletecfg = new deleteconfig(); %>
<%= delectecfg.initiate(); =%>
</BODY>
</HTML>
JSP scripting elements are:
Expressions: <% = expression%> The expression is evaluated and printed out the document.
Scriptlet <% code%> The code is inserted into the servlet service method.
Statements: <%! code%> The code is inserted into the servlet class, outside of any method.
For JSP scripting elements is possible and another syntactic form, based on XML markup:
<jsp:expression> Java expression </ jsp: expression>
<jsp:scriptlet> Java code </ jsp: scriptlet>
<jsp:declaration> Statement Java </ jsp: declaration>
I would prefer the first approach using restFul API. That will be more cleaner approach
So referring to the original problem I have here Google Maps Javascript V3 Uncaught TypeError: Cannot read property 'offsetWidth' of null and after doing a lot of googling, I have found a solution which I thought would be workable which is this How to append multiple Google Maps areas to divs using Handlebars.
However, I have implemented mine in the following way
var EmployeeView = function(employee){
this.render = function(){
$('body').append(this.el);
// inside the new div, put the Handlebars template, with the data from the employee
this.el.html(EmployeeView.template(employee)).ready( function() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
});
return this;
};
this.initialize = function(){
this.el=$("</div>");
window.localStorage.removeItem('paramId');
console.log('removed');
window.localStorage.setItem('paramId',employee);
console.log('added ' + employee.id);
};
this.initialize();
}
EmployeeView.template = Handlebars.compile($("#employee-tpl").html());
Not sure if thats the right way of 'referring' to that solution but now, whenever I run the page, the following error is thrown Uncaught ReferenceError: context is not defined
Anyone got any ideas? and to add, my html is as follows
<body>
<script id="employee-tpl" type="text/x-handlebars-template">
<div class='details'>
<img class='employee-image' src='img/{{firstName}}_{{lastName}}.jpg' />
<ul>
<li>See on map</li>
<li>Share with friends</li>
<li><div id="map-canvas"/></li>
</ul>
<script src="lib/iscroll.js"></script>
<script src="lib/handlebars.js"></script>
<script src="lib/jquery-1.8.2.min.js"></script>
<script src="js/storage/cafe-memory-store.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?APIKEY&sensor=true"></script>
<script src="js/MapView.js"></script>
<script src="js/EmployeeView.js"></script>
<script src="js/HomeView.js"></script>
<script src="js/main.js"></script>
</body>
In this line:
$("employee-tpl").append(HTMLtemplate(context))
You are passing an undefined function and one undefined variable (context).
context should contain he id parameter you defined in your HandlebarJS template to be replaced
See on map
HTMLTemplate in your case is EmployeeView.template which holds the HandlebarJS compiled template: it is a function that receives as arguments the context variable ( or maybe the employee variable?)
If I got it right your code should be:
var EmployeeView = function(employee){
this.render = function(){
$('body').append(this.el);
// inside the new div, put the Handlebars template, with the data from the employee
this.el.html(EmployeeView.template(employee))).ready( function() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
});
return this;
};
this.initialize = function(){
this.el=.$("</div>");
window.localStorage.removeItem('paramId');
console.log('removed');
window.localStorage.setItem('paramId',employee);
console.log('added ' + employee.id);
};
this.initialize();
}
EmployeeView.template = Handlebars.compile($("#employee-tpl").html());
I think you have to pass employee to the template because I saw first_name and last_name in the template.
I'm brand new to perl and javascript and trying to get a javascript for loop to run through a perl array to insert markers into a google maps instance. The map is created and the for loop runs, but 5 of the same marker are inserted because the loop doesn't seem to be running correctly. Is there a better way to access this array in javascript?
#latlongarray = (0,0,20,20);
$length = #latlongarray;
{
print <<HTML;
<html>
<head>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?&sensor=true">
</script>
<script type="text/javascript">
var map ;
function initialize() {
var latlng = new google.maps.LatLng(0,0);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP // can be SATELLITE ,HYBRID, ROADMAP or TERRAIN
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
{
var i;
for (i=0;i<=8;i=i+2)
{
var marker = add_marker($latlongarray[i],$latlongarray[i]);
marker.setMap(map);
}
}
}
</script>
<script type="text/javascript">
function add_marker(lat,lng,title,box_html) {
var infowindow = new google.maps.InfoWindow({
content: box_html
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
title: title
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
return marker;
}
</script>
<title>Reverse IP Lookup & Locate</title>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:80%; height:80%"></div>
</body>
HTML
exit;
}
Perl is server side. It executes BEFORE your Javascript. Perl just outputs HTML and Javascript, once it does that HTML and Javascript has no knowledge of your Perl variables.
You can make a loop in Perl that outputs the appropriate add_marker() Javascript code or you can output a Javascript array and then use a Javascript loop like you are now. You will never be able to reference Perl's array index from the Javascript loop.
As Cfreak pointed you are mixing up your Perl and Javascript code. I recently answered a very similar question in this post