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.
Related
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 am making an html file that basically prints out the coordinates given by the user in a map. Whenever I click the submit button, it returns me an error of "UncaughtReferenceError: NewMap is not defined" i tried using an external javascript and inline javascript but it does not seem to solve the problem. Can you tell me what is wrong with the code?
<!DOCTYPE html>
<html>
<head>
<title>Find My Phone</title>
</head>
<body bgcolor="#2196F3">
<p style="font-size:150%; text-align:center">This is the extension for the app FindMyPhone. In this site, you can view the coordinates where your phone was traced on a map</p>
Latitude:
<input type="number" step="any" id="Lat"/> <br>
Longitude:
<input type="number" step="any" id="Lng"/> <br>
<button onclick="NewMap()">Submit</button>
<div id="map" style="height:500px;width:500px; color:#9E9E9E">
</div>
<script>
function NewMap() {
var mapCanvas = document.getElementById("map").value;
var Latitude = document.getElementById("Lat").value;
var Longitude = document.getElementById("Lng").value;
var mapOptions = {
center: document.getElementById("Lat, Lng")
zoom:15
}
var map = new.google.maps.Map (mapCanvas, mapOptions)
}
</script>
</body>
</html>
P.S: Supposing this code works, will it output the map correctly? Please also show me if it is right or wrong.
Include Google Map Library
You have missed out a comma after center property.
var mapOptions = {
center: document.getElementById("Lat, Lng"),
zoom:15
}
here i got a sample code which shows the same but i like to know from where to arrange the lat lang for any specific country or city.
here map done for London
var london = new L.LatLng(51.505, -0.09);
map.setView(london, 13);
so if some one knows the LatLng for specific country then it is possible. but just tell is there source exist which tell me the latlang for any country or city.
here is full sample code
<html>
<head>
<title>Leaflet Events Example</title>
<link rel="stylesheet" href="leaflet/leaflet.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="leaflet/leaflet.ie.css" /><![endif]-->
<script src="leaflet/leaflet.js"></script>
<script language="javascript">
var map;
var popup = L.popup();
function init() {
map = new L.Map('map');
popup = new L.Popup();
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
maxZoom: 18
}).addTo(map);
map.attributionControl.setPrefix(''); // Don't show the 'Powered by Leaflet' text.
var london = new L.LatLng(51.505, -0.09);
map.setView(london, 13);
map.on('click', onMapClick);
}
//Listener function taking an event object
function onMapClick(e) {
//map click event object (e) has latlng property which is a location at which the click occured.
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(map);
}
</script>
</head>
<body onLoad="javascript:init();">
<div id="map" style="height: 200px"></div> <!-- width equals available horizontal space by default -->
</body>
</html>
Another code
<html>
<head>
<title>Leaflet marker array example</title>
<link rel="stylesheet" href="leaflet/leaflet.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="leaflet/leaflet.ie.css" /><![endif]-->
<script src="leaflet/leaflet.js"></script>
<script language="javascript">
function init() {
var map = new L.Map('map');
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
maxZoom: 18
}).addTo(map);
map.attributionControl.setPrefix(''); // Don't show the 'Powered by Leaflet' text.
var london = new L.LatLng(51.5056,-0.1213);
map.setView(london, 13);
// Define an array. This could be done in a seperate js file.
// This tidy formatted section could even be generated by a server-side script
// or fetched seperately as a jsonp request.
var markers = [
[ -0.1244324, 51.5006728, "Big Ben" ],
[ -0.119623, 51.503308, "London Eye" ],
[ -0.1279688, 51.5077286, "Nelson's Column<br>wp" ]
];
//Loop through the markers array
for (var i=0; i<markers.length; i++) {
var lon = markers[i][0];
var lat = markers[i][1];
var popupText = markers[i][2];
var markerLocation = new L.LatLng(lat, lon);
var marker = new L.Marker(markerLocation);
map.addLayer(marker);
marker.bindPopup(popupText);
}
}
</script>
</head>
<body onLoad="javascript:init();">
<div id="map" style="height: 200px"></div>
</body>
</html>
thanks
If you just want to know the LatLng of any country or city
For example you want to know the LatLng of Australia, Just type this in google
australia lat long like below
Try Google Geocoding API. With this you can get the LatLng of an address.
I've tried all possible solutions but the map just isn't showing. My webview just shows blank.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="theme.css">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<script type="text/javascript">
var map; " +
function initialize() {
var latitude = 0;
var longitude = 0;
if (window.android){
latitude = window.android.getLatitude();
longitude = window.android.getLongitude();
}
var myOptions = {
zoom: 20,
center: myLatLng
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
}
function centerAt(latitude, longitude){
myLatlng = new google.maps.LatLng(latitude,longitude);
map.panTo(myLatLng);
}
</script>
<title>Insert title here</title>
</head>
<body>
<div id="map_canvas" style="height: 100px; width=100px;">This is the map canvas</div>
<script type="text/javascript">initialize();</script>
</body>
</html>
I've narrowed down to this line: map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
When this line is executed, it fails.
Any help is appreciated.
Thanks.
Regards,
Dexter
I can't see myLatLng definition other than in centerAt() function. You need to pass Google Maps LatLng object to the center attribute of myOptions:
var myLatlng = new google.maps.LatLng(latitude, longitude);
var myOptions = {
zoom: 20,
center: myLatLng
}
...
And there is also a strange thing which I can't understand:
var map; " +
^ ^
my bad, submitted the wrong code. Anyway, the major issue here is the connection. That took me a long time to realize it since i was just focusing on the codes.
Thanks.