JavaScript global variable in Google Maps - javascript

I'm making a webapp that allows people to see the location of buses on Google maps. I'm having some problems with global variables in JavaScript. window.variable doesn't work for me. Neither does defining the variable outside the all the functions works. Here is my complete client side code:
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</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 src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see a blank space instead of the map, this
// is probably because you have denied permission for location sharing.
var old = [];
function getLocation()
{
$.get( "http://54.86.161.214/EC_bus_app/get_location.php", function( data ) {
old=[];
var buses = data;
var number_of_buses = buses.slice(0,1);
buses = buses.slice(2);
buses = buses.slice(0,-1);
var bus_coordinates_and_numbers = buses.split(/[ ]+/);
var length_of_array = bus_coordinates_and_numbers.length;
// Turn a single dimensional array into a multi-dimensional array
for (var index = 0; index < bus_coordinates_and_numbers.length; index+= 3)
old.push( bus_coordinates_and_numbers.slice(index, index + 3) );
console.log(old);
//initialize(old);
});
}
setInterval(getLocation, 10000);
var map;
function initialize() {
var mapOptions = {
zoom: 18
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var image = "icon_97.png";
for (i=0;i<old.length; i = i + 1){
var x = old[i][0];
var y = old[i][1];
var myLatlng = new google.maps.LatLng(x,y);
var busMarker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
title: old[i][2]
});
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Your location'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
The variable in question is old. I can pass it to the initialize function from within the get location function using initialize(old);. However, as you can see, I'm using a timer, and initialize(old); causes the entire map to reload again and again, whereas I only want the location markers to load again and again.

Solved the problem by moving getLocation() inside initialize(). But what #geocodezip said in the comments also answers my question completely.

Your problem is not with global variables. It is with asynchronous functions. You need to initialize the map, then request data (asynchronous request), make markers on the map, then periodically update them.

Related

Uncaught error: google is not defined for Google Map API geocoder

Hey Im currently using the Google API to render a map onto my application; however, I am running into a problem where Im using the Google's Geocoding library but it is running into an uncaught error: google is not defined.
I dont understand this error, because I use it to render the map itself, and the google object is being read and rendering the map fine.
Here is my html scripts:
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="js/scripts.js" async></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap" async defer>
</script>
And here is my javascript file:
function initMap() {
var geocoder = new google.maps.Geocoder(),
fromLatLng = getLatLng(geocoder, "Pasadena, California"),
startLatLng = getLatLng(geocoder,"Los Angeles, California"),
fromLocation = new google.maps.LatLng(fromLatLng),
destLocation = new google.maps.LatLng(startLatLng),
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 32.8615616, lng: -117.2188185}, // TODO change to start location
zoom: 7 // continet level
}),
directionService = new google.maps.DirectionsService(),
directionRender = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: fromLocation,
title: "Point A",
label: "A",
map:map
}),
markerB = new google.maps.Marker({
position: destLocation,
title: "Point B",
label:"B",
map:map
});
console.log(fromLocation)
renderRoute(directionService, directionRender, fromLocation, destLocation);
} // end of initMap
function getLatLng(geocoder, address) {
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
if(results[0].geometry.location){
console.log("Successfully Lat/Lng converted");
return results[0].geometry.location;
}
else{
console.log("Couldn't properly convert");
}
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
});
}
I've tried changing around the scripts and a lot of other stackoverflow posts but havent found any luck.
Your geocode use wasn't right.
I have to admit that it was a tricky one!
I never used that service before... I even had to enable it!!
What I found out is that it has a delay to retreive the info.
Yeah... It's a get request after all...
And you do it twice.
So what I did is to set an interval to check if both 2 Geocode resquests callback had executed before setting the map, since needed to set the markers.
I implemented it in a new function which I called doGeocode().
This is also your map API callback in the script call, instead of initMap.
This function, after getting the 2 geocodes latitude/longitude, finally calls the initMap() to render your desired result.
The only thing I couldn't find out is your renderRoute function... Since not provided in your question. But I think you will be able to handle it.
So... Have a look at the result on my server here.
The full code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>SO # 39909383</title>
<link rel="icon" type="image/gif" href="https://www.bessetteweb.com/cube-fallback/images/sept.gif">
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<!-- Google Maps CSS-->
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Open+Sans:300">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
cursor: pointer !important;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
var fromLocation;
var destLocation;
var callbackCounter=0;
function initMap() {
console.log("Map initialisation");
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 32.8615616, lng: -117.2188185}, // TODO change to start location
zoom: 7, // continent level
mapTypeId: google.maps.MapTypeId.SATELLITE // TERRAIN, HYBRYD, ROADMAP
});
var directionService = new google.maps.DirectionsService();
var directionRender = new google.maps.DirectionsRenderer({
map: map
});
var markerA = new google.maps.Marker({
position: fromLocation,
title: "Point A",
label: "A",
map:map
});
var markerB = new google.maps.Marker({
position: destLocation,
title: "Point B",
label:"B",
map:map
});
// renderRoute == not a function!!
// Missing in the question...
// Temporarly commented out.
//
//renderRoute(directionService, directionRender, fromLocation, destLocation);
} // end of initMap
function getLatLng(geocoder, address) {
geocoder.geocode({'address': address}, function(results, status) {
console.log("callbackCounter: "+callbackCounter);
if (status === 'OK') {
if(results[0].geometry.location){
console.log("Successfully Lat/Lng converted");
// Only to see clearly in console.log()
var latlong = JSON.stringify(results[0].geometry.location);
console.log( latlong );
latlong = JSON.parse(latlong);
callbackCounter++;
// Set from
if(callbackCounter==1){
fromLocation = latlong;
}
// Set dest
if(callbackCounter==2){
destLocation = latlong;
}
// Function end.
return;
}
else{
console.log("Couldn't properly convert");
}
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
});
}
function doGeocode(){
var geocoder = new google.maps.Geocoder();
getLatLng(geocoder, "Pasadena, California");
getLatLng(geocoder,"Los Angeles, California");
// Wait for from and dest locations found ( Geocoder get delay )
var waitForCoords = setInterval(function(){
console.log("--- Interval");
if(callbackCounter==2){
clearInterval(waitForCoords);
console.log("--- Interval cleared");
// Ready to initialise the map!
initMap();
}
},50);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]&callback=doGeocode"></script>
</body>
</html>

how to show user location on Google maps using "onclick" function?

I'm trying to build a website that shows a map and on top of it I want to display a button that takes you to your current location.
I'm using Google maps service to pull out the map, I also manage to get the user location by itself so all the JavaScript seems to be working fine but when add the function getlocation to the code and try to call it from the HTML it doesn't work. I believe that is probably not finding the function and I can't figure out why?
I will leave the code below:
<script>
var map;
function initialize() {
var miami = new google.maps.LatLng(41.85, -87.65);
var mapOptions = {
zoom: 4,
center: miami,
disableDefaultUI: true,
}
map = new google.maps.Map(document.getElementById('mymap'),
mapOptions);
var myloc = document.getElementById("try");
function getlocation () {
//code
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I'm using inline style for everything. I'm somehow new into this of JavaScript so if could please tell me where is my error or what else do I need to make a button from the HTML call a function on JavaScript.
In addition here is the HTML button and map div
<style>
html, body, #mymap{
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<body>
<div id="try"><button onclick="getlocation()">Click here</button></div>
<div id="mymap"></div>
</body>
If you don't understand what my question is please also comment!
This is my first question here!
google.maps.event.addListener(map, 'click', function(event) {
marker = new google.maps.Marker({position: event.latLng, map: map});
});

Can't get google map to display on wordpress page

I am new to google maps api and am using it to put a map on my wordpress page and get the location of the user. So far, I have kept the following code in my header.php file with myapikey replaced with my actual api key.
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?libraries=places&key=myapikey"></script>
I also have a wordpress page with the following code. This code works when I keep it on a html file. However, when I put this code on my wordpress page, I don't even get the map to show. I am using Google Maps API v3 Geolocation. Could someone please help me.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta charset="utf-8">
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0 }
#map-canvas { height: 100%; width: 100%; top: -100px;}
</style>
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 12
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
//Html five geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: "HTML5 is used."
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
You can't paste the complete document into the editor, what you put into the editor is expected to be te content of your page, it may be almost anything that you would put into the of a HTML-page(no html, head and body).
script and style always include either via the header/footer of the theme or via a plugin.

Google Map Not appearing even though I'm copying the data directly from the sample code [duplicate]

I'm trying to test some geolocation codes on my computer, but I'm not even able to run the examples.
Although they run perfectly from documentation website when I try to open the html file from my computer I get a blank page, all I do is trying to detect my position...
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<link href="/apis/maps/documentation/javascript/examples/default.css"
rel="stylesheet" type="text/css">
<!--
Include the maps javascript with sensor=true because this code is using a
sensor (a GPS locator) to determine the user's location.
See: http://code.google.com/apis/maps/documentation/javascript/basics.html#SpecifyingSensor
-->
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var map;
function initialize() {
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
Please help, can you find out what am I doing wrong?
You need change the link in the stylesheet to an absolute link:
<link href="http://code.google.com//apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css">

Fetching nearby locations from google places and adding markers on google map from results

EDIT: SOLVED. Correct code below the problem code.
I'm having trouble getting my code to work. What I want to do is to use geolocation to determine the users location. I then want to do a search to locate something from a string (in this case, "Systembolaget", in a radius of 2000, and show the results on a google map. I get my own location on the map, but i'm having big trouble getting the places results.
What am I doing wrong? I don't have that much experience from javascript, so all help is good help.
If you're wondering about the cordova script, it's necessary since I'm doing a phonegap application.
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script src="cordova-1.6.0.js"></script>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=MYAPIKEY&sensor=true"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script type="text/javascript">
// Determine support for Geolocation and get location or give error
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}
// Success callback function
function displayPosition(pos) {
var mylat = pos.coords.latitude;
var mylong = pos.coords.longitude;
//Load Google Map
var latlng = new google.maps.LatLng(mylat, mylong);
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Places
var request = {
location: latlng,
radius: '2000',
name: ['Systembolaget']
};
var service = new google.maps.places.PlacesService(map);
service.search( request, callback );
function callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for ( var i = 0; i < results.length; i++ )
{
var place = results[i];
var loc = place.geometry.location;
var marker = new google.maps.Marker
({
position: new google.maps.LatLng(loc.Pa,loc.Qa)
});
marker.setMap(map);
}
}
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"You are here"
});
}
// Error callback function
function errorFunction(pos) {
alert('It seems like your browser or phone has blocked our access to viewing your location. Please enable this before trying again.');
}
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
SOLVED! CORRECT CODE!
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
<title name="title"></title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="cordova-1.6.0.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script type="text/javascript">
// Determine support for Geolocation and get location or give error
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}
// Success callback function
function displayPosition(pos) {
var mylat = pos.coords.latitude;
var mylong = pos.coords.longitude;
//Load Google Map
var latlng = new google.maps.LatLng(mylat, mylong);
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Places
var request = {
location: latlng,
radius: '20000',
name: ['whatever']
};
var service = new google.maps.places.PlacesService(map);
service.search( request, callback );
function callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"You're here"
});
}
// Error callback function
function errorFunction(pos) {
alert('It seems like your browser or phone has blocked our access to viewing your location. Please enable this before trying again.');
}
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
It's hard to give you specific help, because you haven't really described exactly how you are failing. But one thing I notice right away is that you appear to be trying to load the google.maps script twice, with different sensor information in each. In your first google.maps script tag you include the literal text MYAPIKEY which is has to be incorrect. If you had a real key in a variable, I would expect something like:
src="http://maps.googleapis.com/maps/api/js?key=" + MYAPIKEY + "&sensor=true"
And then in your second script tag you appear to load the places library correctly, but then your sensor tag is set as: sensor-false. Your 2nd script tag appears more correct to me, so I would suggest removing the first script tag as a start.
From there, can you provide more detail about how your page is failing and maybe a link to the page?
Some additional observations:
Your initial if-else looks as if it will call the displayPosition function, but the code within displayPosition will not load the google map; it simply creates some vars that then go out of scope when the function ends.
Outside of the displayPosition function, you create a new instance of the google Map, but it references myOptions, which no longer exists at this point in the code, because it only existed within the scope of the displayPosition function.
I would suggest changing the code related to Map creation to something like:
var map = null;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}
// Success callback function
function displayPosition(pos) {
var mylat = pos.coords.latitude;
var mylong = pos.coords.longitude;
//Load Google Map
var latlng = new google.maps.LatLng(mylat, mylong);
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

Categories

Resources