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.
Related
I have a java client which receive from the server longitude and latitude and i need to send these coordinates as a parameter to an html file which is google map to locate these coordinates i need a way to open html file with passing parameters.
Thanks :)
here's the html code
<!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>
<div id="googleMap" style="width:100%;height:400px;"></div>
<script>
function myMap() {
var mapProp = {
center:new google.maps.LatLng(51.508742,-0.120850), //coordinates
zoom:5,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=myMap"></script>
</body>
</html>
I am trying to display and center a map for the users current location. Everything works fine if I manually enter a hard coded latitude and longitude, but these needs to be dynamic as one user often changes location.
I suspect I am making a basic mistake, but my logic seems like it is correct to me. Please check my work and let me know what I am doing wrong? The line that is remarked out with Latitude and Longitude is the line I want to use instead of the previous line with the hard coded values.
<!DOCTYPE html>
<html>
<head>
<title>W123</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
</head>
<body>
<div id='printoutPanel'></div>
<div id='myMap' style='width: 100vw; height: 100vh;'></div>
<script type='text/javascript'>
function showlocation() {
navigator.geolocation.getCurrentPosition(getLocation);
}
function getLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
}
function loadMapScenario() {
var mapOptions = {
credentials: 'My API key code goes here',
center: new Microsoft.Maps.Location(39.1887643719098, -92.8261546188403),
//center: new Microsoft.Maps.Location(latitude, longitude),
mapTypeId: Microsoft.Maps.MapTypeId.road,
zoom: 8
};
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), mapOptions);
var urlTemplate = 'http://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-{timestamp}/{zoom}/{x}/{y}.png';
var timestamps = ['900913-m50m', '900913-m45m', '900913-m40m', '900913-m35m', '900913-m30m', '900913-m25m', '900913-m20m', '900913-m15m', '900913-m10m', '900913-m05m', '900913'];
var tileSources = [];
for (var i = 0; i < timestamps.length; i++) {
var tileSource = new Microsoft.Maps.TileSource({
uriConstructor: urlTemplate.replace('{timestamp}', timestamps[i])
});
tileSources.push(tileSource);
}
var animatedLayer = new Microsoft.Maps.AnimatedTileLayer({ mercator: tileSources, frameRate: 500 });
map.layers.insert(animatedLayer);
}
</script>
<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=experimental&callback=loadMapScenario' async defer></script>
</body>
</html>
You want to pass in the latitude and longitude into your loadMapScenario function as seen below
function loadMapScenario(latitude,longitude) {
....your code here....
}
Change your callback in the bing map include to a new function like "mapUserLocation" then have mapUserLocation perform the following tasks
function mapUserLocation() {
// code here to get the latitude and longitude from users position
loadMapScenario(latitude,longitude);
}
I have my page so that it allows the user to see their latitude and longitude. I've embedded a google map so that the user can click physically see where they're at. This is a project for my computer science class, so I don't want you to physically write the code for me. I just want suggestions on how to solve this. Here's what I have right now.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<!-- This page will allow the suer to track their location through means of the HTML5 Geolocation feature -->
<title>Assignment 4:Track My Location</title>
<meta name="author" content="Alan Sylvestre" />
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function myLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationReveal);
} else {
alert("Please use a different browser that supports geolocation.");
}
}
window.onload = myLocation;
function locationReveal(position) {
showMap(position.coords);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById("location");
div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}
var map;
function showMap(coords) {
var googleLatAndLong = new google.maps.LatLng(coords.latitude, coords.longitude);
var mapOptions = {
zoom : 18,
center : googleLatAndLong,
mapTypeId : google.maps.MapTypeId.SATELLITE
};
var mapDiv = document.getElementById("map");
map = new google.maps.Map(mapDiv, mapOptions);
addMarker(googleLatAndLong);
}
google.maps.Map(mapDiv, mapOptions);
var marker;
function addMarker(latlong) {
var markerOptions = {
position : latlong,
map : map
};
marker = new google.maps.Marker(markerOptions);
}
var center;
function calculateCenter() {
center = map.getCenter();
}
</script>
</head>
<body style="background-color:yellow;" text="blue;">
<div align="center">
<h1>Reveal My Location</h1>
<p>
You know what's pretty cool? Tracking your location using a simple internet connection. By clicking this button, you're browser will track a global database and reveal your location in terms of latitude and longitude. Enjoy!
</p>
<div id="location"></div>
<br>
<div id="map" style="width:400px; height:400px;"></div>
<br>
<input type="button" id="centerOfMap" value="Center" onclick="calculateCenter()">
<footer>
<p>
© Copyright by Alan Sylvestre
</p>
</footer>
</div>
</body>
First you need to make sure that the DOM is loaded before you run your JavaScript.
That is why 'mapDiv' is 'undefined'.
Either wrap your script in a window.onload anonymous function or push it to just before the closing body tag.
I'm trying to load a Google map into Windows Store Application. However, having a problem with a native Windows RT function: Windows.UI.Popups.MessageDialog. I'm guessing that the Windows namespace is out of scope, but I can't figure out now to get this function into a scope that will make the Windows namespace accessible. Any help is appreciated.
EDIT: the more I think about this, the more I think it has something to do with the fact that I am loading map.html as the source for an iFrame. So the context of map.html is an iFrame, not a Windows Store App page. I guess the Windows namespace is not available from within an iFrame?
From home.html:
<iframe id="getLocationFrame" src="ms-appx-web:///pages/map/map.html" style="width:600px; height:600px;"></iframe>
Exception:
SCRIPT5009: Unhandled exception at line 50, column 17 in ms-appx-web://76ad865e-25cf-485c-bc77-e18186bfd7ee/pages/map/map.js
0x800a1391 - JavaScript runtime error: 'Windows' is undefined
File: map.js, Line: 50, Column: 17
map.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="//Microsoft.WinJS.1.0/js/base.js"></script>
<script type="text/javascript" src="//Microsoft.WinJS.1.0/js/ui.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js? sensor=false"></script>
<script type="text/javascript" src="map.js"></script>
<link href="/pages/map/css/map.css" rel="stylesheet" />
<link href="//Microsoft.WinJS.1.0/css/ui-light.css" rel="stylesheet" />
</head>
<body>
<p>Click to get your location.</p>
<button id="getLocation">Get Location</button><br/>
<div id="mapcontainer"></div><br />
<small>
<a id="anchorLargerMap" href="" style="color:#0000FF;text-align:left" target="_blank">View Larger Map</a>
</small>
</body>
</html>
map.js:
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/map/map.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
//Button "getLocation" event handler
function getLocationClickHandler(eventInfo) {
var myOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapcontainer = document.getElementById("mapcontainer");
var map = new google.maps.Map(mapcontainer, myOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationSuccess, locationFail);
}
}
var namespacePublicMembers = {
locationSucessFunction: locationSuccess,
locationFailFunction: locationFail,
getLocationClickEventHandler: getLocationClickHandler
};
WinJS.Namespace.define("mapPage", namespacePublicMembers);
var getLocationButton = document.getElementById("getLocation");
getLocationButton.addEventListener("click", getLocationClickHandler, false);
function locationSuccess(position) {
var initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
var marker = new google.maps.Marker({
position: initialLocation,
map: map,
title: "You are here."
});
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var url = "http://maps.google.com/maps?q=" + latitude + "," + longitude + "&zoom=13&markers=" + latitude + "," + longitude;
$("#anchorLargerMap").attr('href', url);
}
function locationFail() {
var md = new Windows.UI.Popups.MessageDialog("Could not find you!", "").showAsync; -- ********* THIS LINE THROWS EXCEPTION *********
}
}
});
})();
Code that is executed in the web compartment - your URL says that's where this code is - cannot access WinRT components. You'll need to use postMessage etc to communicate between the two security contexts.
from Map.js:
function locationFail() {
//Can't do this due the the iFrame container
//var md = new Windows.UI.Popups.MessageDialog("Could not find you!", "").showAsync;
window.parent.postMessage("Could not find you!", "*");
}
from Home.js:
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/home/home.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
window.addEventListener("message", messageReceived, false);
function messageReceived(e) {
if (e.origin === "ms-appx-web://76ad865e-25cf-485c-bc77-e18186bfd7ee") {
var md = new Windows.UI.Popups.MessageDialog(e.data, "");
md.showAsync();
}
};
}
});
})();
I got the solution from this blog: http://css.dzone.com/articles/use-winjs-post-message-iframe
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