context is not defined JavaScript - javascript

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.

Related

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.

calling angular Controller/Function from Javascript [duplicate]

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

0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'getElementsByTagName'

I have a simple MVC application in which i want to show location dynamically from Google map.
I am getting this Error in this file----
Unhandled exception at line 16, column 59007 in https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'getElementsByTagName'
The View page contains simple html with javaScript code and some javaScript files included----
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Google Maps </h1>
<div align="left">
<input type="text" value="" id="searchbox" style=" width:800px;height:30px; font-size:10px; margin-top: 7px;">
</div>
<div align="left" id="map" style="width:800px; height: 600px; margin-top: 10px;">
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
var mapOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.06000, 28.98700)
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var geocoder = new google.maps.Geocoder();
$(function () {
$("#searchbox").autocomplete({
source: function (request, response) {
if (geocoder == null) {
geocoder = new google.maps.Geocoder();
}
geocoder.geocode({ 'address': request.term }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var searchLoc = results[0].geometry.location;
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(lat, lng);
var bounds = results[0].geometry.bounds;
geocoder.geocode({ 'latLng': latlng }, function (results1, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
if (results1[1]) {
response($.map(results1, function (loc) {
return {
label: loc.formatted_address,
value: loc.formatted_address,
bounds: loc.geometry.bounds
}
}));
}
}
});
}
});
},
select: function (event, ui) {
var pos = ui.item.position;
var lct = ui.item.locType;
var bounds = ui.item.bounds;
if (bounds) {
map.fitBounds(bounds);
}
}
});
});
});
Want to answer my own question...................I think those old javaScript library file were not compatible with the new versions of IE9. So, I just changed the referenced js libraries files to latest one from this page....developers.google.com/speed/libraries and everything is working fine now....
you can include jquery migrate js file in your project to resolve this. http://code.jquery.com/jquery-migrate-1.2.1.js
I wish I can put this as a comment but I dont have enough reps...
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'Show'
The error above led me to this question and when I didn't find my answer, I looked at it again and the answer was much simpler - I miss-typed 'show' as 'Show'.
$('#Member').closest('.form-group').Show();
I changed it back to lowercase 's'- .show() - I hope this alerts someone else.
I add letest version of jquery and solved problem...
Like...."jquery-1.10.2.js"
.
..

Dojo FilteringSelect shows up as plain text box

I am just beginning to try out Dojo for use with ESRI ArcGIS Server. I have tried a few tutorials and I'm having a problem with the Dojo FilteringSelect Dijit.
Relevant sections of my code:
<script>
dojo.require("esri.map");
dojo.require("esri.tasks.query");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.form.FilteringSelect");
var map;
function init() {
map = new esri.Map("mapDiv",{
basemap: "streets",
center: [-80.94, 33.646],
zoom: 8
});
dojo.connect(map, "onLoad", initFunctionality);
}
function initFunctionality(map) {
//build query task
var queryTask = new esri.tasks.QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/3");
//build query filter
var query = new esri.tasks.Query();
query.returnGeometry = true;
query.outFields = ["NAME", "POP2000", "POP2007", "POP00_SQMI", "POP07_SQMI"];
query.where = "STATE_NAME = 'South Carolina'";
query.outSpatialReference = {"wkid":102100};
var infoTemplate = new esri.InfoTemplate();
infoTemplate.setTitle("${NAME}");
infoTemplate.setContent( "<b>2000 Population: </b>${POP2000}<br/>"
+ "<b>2000 Population per Sq. Mi.: </b>${POP00_SQMI}<br/>"
+ "<b>2007 Population: </b>${POP2007}<br/>"
+ "<b>2007 Population per Sq. Mi.: </b>${POP07_SQMI}");
map.infoWindow.resize(245,105);
//Can listen for onComplete event to process results or can use the callback option in the queryTask.execute method.
dojo.connect(queryTask, "onComplete", function(featureSet) {
map.graphics.clear();
var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,255,255,0.35]), 1),new dojo.Color([125,125,125,0.35]));
//QueryTask returns a featureSet. Loop through features in the featureSet and add them to the map.
dojo.forEach(featureSet.features,function(feature){
var graphic = feature;
graphic.setSymbol(symbol);
graphic.setInfoTemplate(infoTemplate);
map.graphics.add(graphic);
});
});
queryTask.execute(query);
}
function initLineID(features) {
var lineIdObjects = [];
dojo.forEach(features.features, function(feature) {
lineIdObjects.push({"name": feature.attributes.field_name});
});
//Build the appropriate data object for our data component
var data = {
"identifier": "name",
"items": lineIdObjects
}
//bind the data object to the datastore
var lineDataStore = new dojo.data.ItemFileReadStore({data: data});
//bind the data store to the FilteringSelect component
dijit.byId("lineid").store = lineDataStore;
}
dojo.ready(init);
</script>
as well as
<input dojoType="dijit.form.FilteringSelect"
id="lineid"
searchAttr="name"
name="widgetName"
onChange="doSomething(this.value)">
The challenge I face is that the resulting page only shows a basic
<input type="text">
box. Anyone know why this is? Thanks.
My guess is that you haven't configured a theme. You can do so by adding stylesheets and modifying the body element.
In this example, I am using the claro theme.
<link href="PATH_TO/dojo/resources/dojo.css" rel="stylesheet">
<link href="PATH_TO/dijit/themes/dijit.css" rel="stylesheet">
<link href="PATH_TO/dijit/themes/tundra/tundra.css" rel="stylesheet">
Add the theme name to the body element.
<body class="tundra">
parseOnLoad was set to false. For my future reference, why would I want to leave it at false?

Windows Store App - WinJS: 0x800a1391 - JavaScript runtime error: 'Windows' is undefined

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

Categories