I'm trying to pass in the initial start values from a text file on the localhost.
Can someone please explain how to do this properly?
I've been trying to follow tutorials but they all assume the file is read in from a reader.
I don't know javascript very well.
This doesn't work
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script>
function initialize() {
var lat = 0;
var long = 0;
var center = File("Center.txt");
var reader = new FileReader();
reader.onload = function (e) {
var results = reader.result;
}
reader.readAsText(center);
var text = reader.result.toString();
var stringAr = text.split(",");
lat = stringAr[0];
long = stringAr[1];
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(lat, long)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
map.data.loadGeoJson('test.json');
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
If I comment out all the file reader stuff it works, but I need to be able to pass in the lat long parameters without the user selecting anything.
Would I alternatively be able to read them from a json file and set it that way the same way I am with the data?
The problem is probably that the values you're reading from your text file are being saved as strings. Google maps expects Number objects. You can simply use parseFloat() to fix this:
lat = parseFloat(stringAr[0]);
long = parseFloat(stringAr[1]);
Related
I am trying to open a Google Maps InfoWindow to show an image but I want to define the image source with a javascript variable.
Here's my Python code using Flask.
import os
from flask import Flask, render_template
from flask_jsglue import JSGlue
# Start the Flask application
app = Flask(__name__)
jsglue = JSGlue(app)
# Get the Google Maps API key from the file
with open(os.getcwd() + '/data/GoogleMapsAPIkey.txt') as f:
APIkey = f.readline()
f.close
app.config['API_KEY'] = APIkey
#app.route('/')
def index():
return render_template('./test.html', key=APIkey)
if __name__ == '__main__':
app.run(debug=False)
And here's the HTML I am using.
<!DOCTYPE html>
<html>
<head>
<title>Thumb in window test</title>
{{ JSGlue.include() }}
<meta charset="utf-8">
<style>
#map-canvas {
width: 100%;
height: 500px;
}
</style>
</head>
<body>
<div id="map-canvas">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var map;
var thumbWindow;
function showMap(){
// Create the map
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {lat: -37.8135, lng: 144.9655},
zoom: 14
});
google.maps.event.addDomListener(map, 'click', showThumb);
}
function showThumb(){
thumbWindow = new google.maps.InfoWindow();
thumbWindow.setContent('<img id="thumb" src="/static/thumbs/2_thumb.JPG" align="middle">');
thumbWindow.setPosition(map.getCenter());
thumbWindow.open(map);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key={{ key }}&callback=showMap">
</script>
</body>
</html>
This is all working as expected but only if I fully state the image URL in the src.
If I replace the showThumb function with this....
function showThumb(){
var number = 2;
var file = "/static/thumbs/" + number.toString() + "_thumb.JPG";
thumbWindow = new google.maps.InfoWindow();
thumbWindow.setContent('<img id="thumb" src="" align="middle">');
thumbWindow.setPosition(map.getCenter());
thumbWindow.open(map);
document.getElementById("thumb").src=file;
}
... I get an empty InfoWindow and an Uncaught TypeError: Cannot set property 'src' of null error.
It seems that Javascript can't recognise ids in an InfoWindow.
Anyone got a way to get this working?
Seems the I asked the question a bit too soon. I had a revelation and found a solution.
The answer was to not use an element id at all.
function showThumb(){
var number = 2;
var file = "/static/thumbs/" + number.toString() + "_thumb.JPG";
var imgCode = '<img id="thumb" src=' + file + ' align="middle">'
thumbWindow = new google.maps.InfoWindow();
thumbWindow.setContent(imgCode);
thumbWindow.setPosition(map.getCenter());
thumbWindow.open(map);
}
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 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'm trying to follow this Google Maps example, but instead of hardcoding my API KEY, I'm trying to fetch it from an API I created.
So, I created this HTML file. The KEY is properly fetched, but when I'm trying to set the script's src attribute on runtime (so I can add my own key to the URI), it's not getting added at all.
This is my HTML
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers example</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
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!'
});
}
</script>
<script async defer>
$.get( "maps_api_key", function( data ) {
const API_KEY = String(data)
console.log("API_KEY: " + API_KEY)
var uri = "https://maps.googleapis.com/maps/api/js?key=" + API_KEY + "&callback=initMap"
console.log("URI is: " + uri)
$("#maps_fetcher").attr("src", uri)
});
</script>
<script id="maps_fetcher" async defer
src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
console.log("Map fetcher")
</script>
</body>
</html>
The line at console.log("Map fetcher") is never being printed either.
For what it's worth, I'm serving the HTML through Node and Express.
Any ideas on what could be happening here?
Thanks in advance
I´m trying to put a google maps image into my HTML page. I cannot touch the <head> section as the page is dynamically loaded using PHP code (this logic is not explained here).
So, I´ve build the following HTML test code, that doesn´t work - the maps does not appear on screen.
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta charset="UTF-8" />
<title>TEST PAGE</title>
</head>
<body>
<h1>Maps test page.</h1>
<script type="text/javascript">
function initialize() {
alert("Initialize");
var mapCanvas = document.getElementById("mapCanvas");
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
}
var map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addDomListener(window, "load", initialize);
}
window.onload = function() {
alert("Onload");
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js";
document.body.appendChild(script);
}
</script>
<div id="mapCanvas" style="width: 650px; height: 350px;"></div>";
<script type="text/javascript"> initialize() </script>
</body>
</html>
The alerts are coming up, but no map is shown...
Help is appreciated to make is work.
Asynchronously load the Google Maps Javascript API, use the callback parameter to run your initialize function.
working example
<html lang="en-us">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta charset="UTF-8" />
<title>TEST PAGE</title>
</head>
<body>
<h1>Maps test page.</h1>
<script type="text/javascript">
function initialize() {
alert("Initialize");
var mapCanvas = document.getElementById("mapCanvas");
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
}
var map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addDomListener(window, "load", initialize);
}
window.onload = function() {
alert("Onload");
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?callback=initialize";
document.body.appendChild(script);
}
</script>
<div id="mapCanvas" style="width: 650px; height: 350px;"></div>";
</body>
</html>
The problem is that initialize() is getting executed before the Google Maps Javascript has been added to the page. You aren't importing the Google Maps JS until the DOM has finished loading, in your window.onload callback. Try this instead:
<div id="mapCanvas" style="width: 650px; height: 350px;"></div>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
alert("Initialize");
var mapCanvas = document.getElementById("mapCanvas");
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map(mapCanvas, mapOptions);
}
window.onload = function() {
initialize();
};
</script>