Google Maps refresh traffic layer - javascript

In my Rails app, the background consists of a fullscreen div with Google Maps and a traffic layer.
This is what gets called on page load:
$(function () {
updateMap();
});
The updateMap function creates a Google Map on the div element 'google_map':
function updateMap() {
var latlng = new google.maps.LatLng(52.157927, 4.704895);
var myOptions = {
zoom: 10,
center: latlng,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("google_map"),
myOptions);
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
updateTrafficOnMap(map, trafficLayer);
}
The last call is to this function:
function updateTrafficOnMap(map, overlay)
{
overlay.setMap();
overlay = null;
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
setTimeout(function(){ updateTrafficOnMap(map, trafficLayer) }, 60000);
}
Which is supposed to update the traffic layer every minute.
Now the div is loaded correctly on page load, the layer is loaded too. However, this never updates, so there's no real time traffic information unless you reload the whole page.
Anyone knows the magic word to make the traffic layer refresh properly?

So I found the answer. Apparently you cannot update the map with a new overlay while inside the timeOut function. I do not know why exactly (as for instance a 'alert()' does show while inside the function). I solved it using a switch statement in the updateOnTrafficMap function, so that once every minute the layout disappears, and immediately reappears using another timeOut (set to 1 ms).
function updateMap() {
// the following creates a Google Map with zoom level 10 and the LatLong coordinates
// stated below
var latlng = new google.maps.LatLng(52.053335, 4.917755);
var myOptions = {
zoom: 10,
center: latlng,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("google_map"), myOptions);
updateTrafficOnMap(map, null, 1);
}
function updateTrafficOnMap(map, trafficLayer, on)
{
if(on == 0) {
trafficLayer.setMap(null);
setTimeout(function() { updateTrafficOnMap(map, null, 1) }, 1)
}
if(on == 1) {
var trafficLayer2 = new google.maps.TrafficLayer();
trafficLayer2.setMap(map);
// after 300ms (or 5 minutes) update the traffic map
setTimeout(function() { updateTrafficOnMap(map, trafficLayer2, 0)}, 300000)
}
}
On document load you call the updateMap() function, and you should have a DIV with id "google_map" to display the map in of course.

This worked for me:
var _mainMap = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var _gmapTrLayer = new google.maps.TrafficLayer();
_gmapTrLayer.setMap(_mainMap);
setInterval(refreshGmapsTrafficLayer, 60000); // runs every minute
function refreshGmapsTrafficLayer() {
_gmapTrLayer.setMap(null);
_gmapTrLayer.setMap(_mainMap);
}

A setInterval over the whole initialize routine got me the refreshing that I desired. options.ts_google_map_traffic_refresh_milliseconds is set to the milliseconds you desire.
setInterval(_ts_map_initialize, options.ts_google_map_traffic_refresh_milliseconds);
function _ts_map_initialize(){
console.log('function _ts_map_initialize()')
var myLatlng = new google.maps.LatLng(options.ts_google_map_traffic_latHome,options.ts_google_map_traffic_lonHome);
var myOptions = {
zoom: ts_int_zoomLevel,
center: myLatlng,
panControl: false,
zoomControl: false,
streetViewControl: false,
overviewMapControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles:[{
featureType:"poi",
elementType:"labels",
stylers:[{
visibility:"off"
}]
}]
}
map = new google.maps.Map(document.getElementById('ts_google_map_traffic_canvas'), myOptions);
defaultBounds = map.getBounds();
trafficLayer = new google.maps.TrafficLayer(); //add the layer - don't view it unless user toggles button
trafficLayer.setMap(map);
}
enter code here

Related

One of my variables is being set in initMap, but when I call another function inside the script that same variable is suddenly undefined

I original had this question posted, but wouldn't let me edit post nor resign in. In this I hope to have refocus and make it clear what I am asking for.
I define my map in the callback function of Google Maps Api. initMap is definitely being called first. Once it is I manually trigger the addVehicleMarker method.
This is how it is being called in HTML side:
// index.html
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
<script defer src="../src/map-manager.js"></script>
This is what I am doing in initMap below:
// map-manager.initMap
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: home_latlng,
streetViewControl: false
});
My issue
I want to import my map-manager.js class elsewhere. Mainly for the addVehicleMarker method. When I do the following...
var MapManager = require('../src/map-manager');
MapManager.addVehicleMarker(v);
map in map-manager.js is now undefined.
When I do...
addVehicleMarker(v);
map in map-manager.js has the map which I defined in initMap. Without my even having to import the file.
Question
How can I achieve the same thing in addVehicleMarker(v); while allowing my to import it properly and called it as MapManager.addVehicleMarker(v);, while retaining map?
This is the rest of the source:
// map-manager.js
var VehicleManager = require('../src/vehicle-manager');
var WampTasks = require('../src/wamp-tasks');
var map;
var vehicleMarkers = [];
function initMap() {
const home_latlng = {
lat: 33.816714399999995,
lng: -117.90523610000001
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: home_latlng,
streetViewControl: false
});
}
// http://blog.mridey.com/2010/03/using-markerimage-in-maps-javascript.html
function addVehicleMarker(vehicle) {
console.log(map);
var icon = new google.maps.MarkerImage(
vehicle.iconLocation,
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(32, 32)
);
var marker = new google.maps.Marker({
position: vehicle.currentLatLng,
icon: icon,
map: map
});
console.log(marker);
// marker.setTitle(String(vehicle.displayName));
vehicleMarkers.push(marker);
console.log(vehicleMarkers);
}
module.exports = {};
module.exports["addVehicleMarker"] = addVehicleMarker;
Seems a var scope issue. Declare var map at window level (and remove if presente other nested var maps; delacration
<script>
var map;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: home_latlng,
streetViewControl: false
});
....
</script>

How to show a map focused on a marker using a click event on Google Maps JavaScript API v3?

I created a map that focuses on a user's location. The map has a single marker with an info window. When a user clicks on the info window it gives him a hyperlink to an info page (info.html). I want to create an option that will allow the user to go back from the info page to the map, and the map should be focused on the same marker (not on his current location). It's basically going the opposite way. It sounds pretty simple, but I have no idea how to code this.
I guess I can build a different map for every marker, but that seems highly unlikely to be the right solution. Any help would be appreciated.
This is my attempt with the script, (initialize2() doesn't work):
$(document).ready(function() {
getLocation();
});
var map;
var jones = new google.maps.LatLng(40.59622788325198, -73.50334167480469);
function getLocation() {
navigator.geolocation.getCurrentPosition(
function(position) {
var myLatLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(myLatLng);
},
function() {
alert("Please enable location detection on your device");
}
);
}
function initialize() {
var mapOptions = {
center: map,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var infowindow = new google.maps.InfoWindow({
});
var marker1 = new google.maps.Marker({
position: jones,
map: map
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow.setContent('<h4>Jones Beach</h4>See info');
infowindow.open(map,marker1);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
// this is my attempt to focus on the marker
// there will be a button that will evoke this function from info.html
function initialize2() {
var mapOptions2 = {
zoom: 14,
center: new google.maps.LatLng(40.59622788325198, -73.50334167480469),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions2);
}
google.maps.event.addDomListener(window, 'load', initialize2);
What about using a hash in the url?
Try using "http://students.example.com/test.html#one":
$(function() {
var places = {
one: [40.59622788325198, -73.50334167480469],
two: [50.59622788325198, -71.50334167480469]
};
var div = $('#map-canvas');
var map = new google.maps.Map(div.get(0), {
center: map,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var markers = {};
$.each(places, function(name) {
markers[name] = new google.maps.Marker({
position: new google.maps.LatLng(this[0], this[1]),
map: map
});
});
var place = location.hash.substr(1);
if(place in places) {
map.setCenter(markers[place].getPosition());
}
});

How to add Markers on Google maps v3 API asynchronously?

I've been following the official documentation on how to add markers on the map so far
Nevertheless, I can see only one marker at a time max. If I try to add another one, then it doesn't work (I can't even see the first one).
My process is the following:
I initialize gmaps api:
jQuery(window).ready(function(){
//If we click on Find me Lakes
jQuery("#btnInit").click(initiate_geolocation);
});
function initiate_geolocation() {
if (navigator.geolocation)
{
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyBbfJJVh0jL1X9b7XFDcPuV7nHD1HlfsKs&sensor=true&callback=initialize";
document.body.appendChild(script);
navigator.geolocation.getCurrentPosition(handle_geolocation_query, handle_errors);
}
else
{
yqlgeo.get('visitor', normalize_yql_response);
}
}
Then, I display it on the appropriate div. But when it comes to make the AJAX call, in order to get my locations of the different markers I'd like to display, It just doesn't work properly. Here is the code with a simple map displayed (since that's the only thing working for me so far).
function handle_geolocation_query(position){
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
mapTypeId: google.maps.MapTypeId.SATELLITE
}
alert('Lat: ' + position.coords.latitude + ' ' +
'Lon: ' + position.coords.longitude);
$('#map-canvas').slideToggle('slow', function(){
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
});
$.when( getLakes(position.coords.latitude, position.coords.longitude)).done(function(results) {
// InitializeGoogleMaps(results);
if(results)
var data = results.map(function (lake) {
//Check if the lake has any open swims, if not, the button will not be clickable and an alert will pop up
if (lake.available>0)
clickable=true;
else
clickable=false;
return {
name: lake.name,
fishs: lake.fisheryType,
swims: lake.swims,
dist: lake.distance,
lat: lake.latitude,
long: lake.longitude,
id: lake.id,
avail: lake.available,
clickable: clickable,
route: Routing.generate('lake_display', { id: lake.id, lat: position.coords.latitude, lng: position.coords.longitude})
}
});
var template = Handlebars.compile( $('#template').html() );
$('#list').append( template(data) );
} );
};
So I'd like to add markers after the AJAX call. I've set up a function that I should call in the when()
function InitializeGoogleMaps(results) {
};
to display the markers in a foreach loop but nope, can't make it work. It looks like this :
CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
marker = new google.maps.Marker({
position: location,
map: map
});
Any help would be great !
Thanks
The main issue is that the map variable is declared only in the scope of the anonymous callback on slideToggle. First of all declare at the top-level function scope.
function handle_geolocation_query(position){
var map,
mapOptions = {
zoom: 14,
center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
mapTypeId: google.maps.MapTypeId.SATELLITE
}
...
Then change the slideToggle callback to initialise the variable instead of redeclaring:
$('#map-canvas').slideToggle('slow', function(){
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
});
Then you should pass map as a second parameter to your InitializeGoogleMaps function and call it using InitializeGoogleMaps(results, map). See where this gets you and hit me back with any questions.

Google Map KML layer - click event return ZERO_RESULTS

I am working with the Google Maps KML layer click event.
I am using this code:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(41.875696, -87.624207),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var ctaLayer = new google.maps.KmlLayer('https://sites.google.com/site/anoopkml123/kml/ab9Plan0520.kmz');
ctaLayer.setMap(map);
google.maps.event.addListener(ctaLayer, 'click', function(kmlEvent) {
alert(kmlEvent.featureData.name);
});
}
Sometimes alert(kmlEvent.featureData.name) shows a number but sometimes it's 'undefined'.
Sometimes obj.featuredData.id is null (ZERO_RESULTS status is in status field).
Re-created your code in a fiddle: http://jsfiddle.net/mdares/TAfys/
I cannot replicate the issue you are having. Can you provide an example given the above link of where it fails? Is this possibly browser specific? Finally - is there any additional code you haven't posted which might be the cause? My code is unchanged from yours as you posted, but I am curious if you are also doing other things:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(41.875696, -87.624207),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var ctaLayer = new google.maps.KmlLayer('https://sites.google.com/site/anoopkml123/kml/ab9Plan0520.kmz');
ctaLayer.setMap(map);
google.maps.event.addListener(ctaLayer, 'click', function (kmlEvent) {
alert(kmlEvent.featureData.name);
});
}

how to get all Overlays via KmlLayer class on google-maps-v3 not noly when someone click

i follow this article ,and the code is :
var myLatlng = new google.maps.LatLng(40.65, -73.95);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var nyLayer = new google.maps.KmlLayer('http://www.searcharoo.net/SearchKml/newyork.kml',
{suppressInfoWindows: true});
nyLayer.setMap(map);
google.maps.event.addListener(ctaLayer, 'click', function(kmlEvent) {
var text = kmlEvent.featureData.description;
showInDiv(text);
});
function showInDiv(text) {
var sidediv = document.getElementById('contentWindow');
sidediv.innerHTML = text;
}
but i want to get all Overlays when i load the geo-rss,not only someone click ,
what should i do .
thanks
You need to attach an event that fires on load, however in v3, there is no load. The map is already loaded after you created the map.
I believe just add the overlays at this point.

Categories

Resources