Call two JavaScript functions from one button - javascript

I'm trying to execute two separate functions from one onClick.
It is a dictionary service which returns definitions from Glosbi API and the second function is Google Maps API call that changes the map to what has been searched for.
The first functions works perfectly, but the second function calling Google Maps API doesn't work.
Can anyone see anything in my code that isn't right or needs to be changed? I feel very close!
function codeTerm() {
$(document).ready(function(){
$('#term').focus(function(){
var full = $("#definition").has("definition").length ? true : false;
if(full === false){
$('#definition').empty();
}
});
var getDefinition = function(){
var word = $('#term').val();
if(word === ''){
$('#definition').html("<h2 class='loading'>We haven't forgotten to validate the form! Please enter a word.</h2>");
}
else {
$('#definition').html("<h2 class='loading'>Your definition is on its way!</h2>");
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=" +word+ "&pretty=true&callback=?", function(json) {
if (json !== "No definition has been found."){
var meanings = "";
json["tuc"].forEach(function(tuc) {
if (typeof tuc["meanings"] !== 'undefined') {
tuc["meanings"].forEach(function(m) {
meanings += "<p>"+m["text"]+"</p>\n";
});
}
});
$("#definition").html(meanings);
}
else {
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=&pretty=true" + "?callback=?", function(json) {
console.log(json);
$('#definition').html('<h2 class="loading">Nothing found.</h2><img id="thedefinition" src=' + json.definition[0].image.url + ' />');
});
}
});
}
return false;
};
$('#search').click(getDefinition);
$('#term').keyup(function(event){
if(event.keyCode === 13){
getDefinition();
}
});
});
}
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var country = document.getElementById('search').value;
geocoder.geocode( { 'search': country}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
$('#search').click(country);
$('#term').keyup(function(results){
if(results.keyCode === 13){
country();
}
});
And the HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="author" content="Matthew Hughes">
<meta name="Dictionary" content="A dictionary web service">
<title>Dictionary Web Application</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="dictionary.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCVD1Kaf1yE4M9IcBNRAyujObcY2sGI0J0&sensor=false"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="dictionary.js"></script>
</head>
<body>
<div id="container">
<div id="top">
<header>
<h1>Dictionary Application</h1>
</header>
</div>
<div id="app">
<div id="panel">
<input id="term" type="text" placeholder="Enter a word...">
<button id="search" onclick="codeTerm(); codeAddress();">Define!</button>
</div>
<section id="definition">
</section>
<div id="map-canvas">
</div>
</div>
<footer>
<p>Created by Matthew Hughes</p>
</footer>
</div>
</body>
Thanks!

In the comments you mention 2 errors...
google is not defined
Was the inclusion of the Google API successful? You have this:
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCVD1Kaf1yE4M9IcBNRAyujObcY2sGI0J0&sensor=false"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
Do those references work? In your browser debugging tools, take a look at the network tab. What do these calls return, if anything? It sounds like the API isn't being loaded successfully. Do you need those to be https specifically? Try omitting the protocol so that it defaults to the current page's protocol:
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyCVD1Kaf1yE4M9IcBNRAyujObcY2sGI0J0&sensor=false"></script>
<script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
You're also including one of your JavaScript libraries twice:
<script src="dictionary.js"></script>
That might not break anything, but it also might. In any event, it should only be included once.
country if not defined
You create a variable called country in one of your functions:
function codeAddress() {
var country = document.getElementById('search').value;
// other code
}
So it's scope is within that function only. But you also try to reference it outside of that function, and you try to reference it as a function:
$('#search').click(country);
$('#term').keyup(function(results){
if(results.keyCode === 13){
country();
}
});
So even if it were moved to a global scope, country isn't a function so it's not clear what you're trying to accomplish with these two handlers. Maybe you meant to invoke a different function?

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.

Google API Javascript, How to get the current location on IP-Address and on live site?

I wrote a code that works fine in JSFiddle, also at localhost, it is working fine. But when I move it to IP or on live site of Godaddy domain, it shows blank page! why?
Please Help me to get out of this problem. As I do google and spent a lot of time but not get any solution. Problem is with IP address and live server website. Please give me a solution if you know about this problem.
Here is the code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="//maps.googleapis.com/maps/api"></script>
<script src="scripts/jquery-3.2.1.min.js"></script>
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyB3_ve60J0oE7IXz-LTuE0SqaWI8MWP9uQ&callback=requestPosition" ></script>
<script type="text/javascript">
function setText(val, e) {
document.getElementById(e).value = val;
}
function insertText(val, e) {
document.getElementById(e).value += val;
}
var nav = null;
function requestPosition() {
if (nav == null) {
nav = window.navigator;
}
if (nav != null) {
var geoloc = nav.geolocation;
if (geoloc != null) {
geoloc.getCurrentPosition(successCallback);
}
else {
alert("geolocation not supported");
}
}
else {
alert("Navigator not found");
}
}
function successCallback(position)
{
setText(position.coords.latitude, "latitude");
setText(position.coords.longitude, "longitude");
var latlng = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map124"), myOptions);
var marker = new google.maps.Marker
(
{
position: new google.maps.LatLng(position.coords.latitude,
position.coords.longitude),
map: map,
title: 'Click me'
}
);
}
</script>
</head>
<body>
<label for="latitude">Latitude: </label><input id="latitude" /> <br />
<label for="longitude">Longitude: </label><input id="longitude" /> <br />
<input type="button" onclick="requestPosition()" value="Get Latitude and Longitude" />
<div id="map124" style="width:400px;height:400px">
</div>
</body>
</html>

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"
.
..

Centering a google map with javascript from pin

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.

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