using <script> in html page using sightly - javascript

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

Related

How Do I Take An Input From A Textbox And Use It To Search For a Location On Google Maps?

I am working on a project and one of the goals is for the user to put a location's name into a textbox and press a button to search for a location on a Google map.
<h2>How to Use</h2>
<p>To use this program, enter a location then click the button to search for it.</p>
<h2>Search Location</h2>
Location: <input type="text" id="myText" value="">
<!-- This creates a textbox --->
<button onclick="searchFunction()">Search</button>
<!-- This creates a button --->
<p id="demo"></p>
<script>
function searchFunction() {
var location = document.getElementById("myText").value;
}
</script>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h1>Google Map</h1>
<div id="map"></div>
<script>
function initMap() {
var options = {
zoom: 12,
center: {
lat: 39.7684,
lng: -86.1581
}
}
var map = new google.maps.Map(document.getElementById('map'), options);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBhrDQVoc_0FJx4Hy4tsFMKtmX78VNTUhw&callback=initMap">
</script>
<script>
if (location == "Children's Museum") {
function initMap() {
var options = {
zoom: 12,
center: {
lat: 39.810230,
lng: -86.158882
}
}
var map = new google.maps.Map(document.getElementById('map'), options);
var locationTestPosition = {
lat: 39.810230,
lng: -86.158882
};
var marker = new google.maps.Marker({
position: locationTestPosition,
map: map
});
}
</script>
}
This is the code that I currently have. The idea is that the user will insert a place's name and then using an if/else statement, the code will place a marker on the map at the proper coordinates. I cannot seem to get it to work though. I am new to HTML and JavaScript, so this is a lot of learning for me.

Linking Google Script Variable to the Javascript in HTML

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.

Repeatition of map div in ng repeat

I have a card where it is repeated multiple times in a page, In the card I have a google map which shows the location of a particular point.
I am getting the google side response as
Error
at new nc (https://maps.googleapis.com/maps/api/js?key=AIzaSyCEHWgPqgJiWcySMQPZZ7W7Cjpugl928Fw&callback=renderMap:47:499)
at Object._.oc (https://maps.googleapis.com/maps/api/js?key=AIzaSyCEHWgPqgJiWcySMQPZZ7W7Cjpugl928Fw&callback=renderMap:48:96)
at ah (https://maps.googleapis.com/maps/api/js?key=AIzaSyCEHWgPqgJiWcySMQPZZ7W7Cjpugl928Fw&callback=renderMap:98:420)
at https://maps.googleapis.com/maps/api/js?key=AIzaSyCEHWgPqgJiWcySMQPZZ7W7Cjpugl928Fw&callback=renderMap:137:53
at Object.google.maps.Load (https://maps.googleapis.com/maps/api/js?key=AIzaSyCEHWgPqgJiWcySMQPZZ7W7Cjpugl928Fw&callback=renderMap:21:5)
at https://maps.googleapis.com/maps/api/js?key=AIzaSyCEHWgPqgJiWcySMQPZZ7W7Cjpugl928Fw&callback=renderMap:136:20
at https://maps.googleapis.com/maps/api/js?key=AIzaSyCEHWgPqgJiWcySMQPZZ7W7Cjpugl928Fw&callback=renderMap:137:68
Html code is as follows
<div class="body" ng-repeat="hospital in hospitals">
<div class="list card">
<div>
<div id="map{{$index}}" style="height:200px;width:100%;" class="renderMap(hospital)"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=myKey&callback=renderMap">
</script>
</div>
</div>
</div>
In controller, it is as follows
$scope.renderMap = renderMap;
function renderMap(hospital){
$scope.details_for_map = hospital;
console.log($scope.details_for_map);
initMap();
}
function initMap() {
var latlng = new google.maps.LatLng( $scope.details_for_map.geometry.location.lat, $scope.details_for_map.geometry.location.lng);
var map = new google.maps.Map(document.getElementById('map'+$scope.details_for_map.index), {
zoom: 4,
center: latlng
});
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Hello World!'
});
}
As I am new to ionic and angular js I am not able to figure out what I am doing incorrectly. Please let me know what I can do about it.

Pass MSSQL table values to javascript

I'm trying to make a website with asp.net mvc 4 & EF6 where I want to pass values from MSSQL table to javascript. So far everything is working fine except if I pass Latitude & Longitude values for google-map-api function, map doesn't show up in my view. I used Html.HiddenFor helper to pass the value from <span>. Here are my codes,
Controller
public ActionResult BranchDetails(int BrId)
{
Branch branchDetails = abdb.Branches.Find(BrId);
return View(branchDetails);
}
View
<script>
function initialize() {
var marker;
var LatTag = document.getElementById("Lat");
var Lat = LatTag.getElementsByTagName("span");
var LngTag = document.getElementById("Lng");
var Lng = LngTag.getElementsByTagName("span");
var mapProp = {
center: new google.maps.LatLng(LatTag, LngTag),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
marker = new google.maps.Marker({
position: new google.maps.LatLng(Lat, Lng),
animation: google.maps.Animation.BOUNCE
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div class="container well" style="min-width: 100%; padding-right: 5px;">
<div id="googleMap"></div>
<span id="Lat">#Html.HiddenFor(model => model.Latitude)</span>
<span id="Lng">#Html.HiddenFor(model => model.Longitude)</span>
<h4><b>#Html.DisplayFor(model => model.Title)</b></h4>
<p><strong>Address:</strong> #Html.DisplayFor(model => model.Address)</p>
<p><strong>Contact No. :</strong> #Html.DisplayFor(model => model.ContactNo)</p>
<p><strong>Contact Person(s):</strong> #Html.DisplayFor(model => model.ContactPerson)</p>
</div>
</body>
Point to be noted that my Longitude & Latitude fields in MSSQL are set in varchar mode. I'm not sure if its causing the problem but just felt needed to inform. How can I solve this problem? Need this help badly. Tnx.
Nevermind, found my own solution. This worked for me, instead of giving span id, I gave Html.HiddenFor helper the id. For some reason javascript was not picking the id of the span I guess. Here are my codes,
<script>
function initialize() {
var marker;
var Lat = parseFloat(document.getElementById("Lat").value);
var Lng = parseFloat(document.getElementById("Lng").value);
var mapProp = {
center: new google.maps.LatLng(Lat, Lng),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
marker = new google.maps.Marker({
position: new google.maps.LatLng(Lat, Lng),
animation: google.maps.Animation.BOUNCE
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div id="googleMap"></div>
#Html.HiddenFor(model => model.Latitude, new { id = "Lat" })
#Html.HiddenFor(model => model.Longitude, new { id = "Lng" })
</body>

Javascript Forloop withing Perl Not Working for Google Maps API to create Markers

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

Categories