I am trying to create a map with data exported from my Google Fusion Tables. The problem is, I have so many data to be displayed including text and images. And I want to create info windows with tabs.
How will I be possibly display infobubble when I click on a marker? The code that I have now to retrieve Google Fusion Tables data is:
layer = new google.maps.FusionTablesLayer({
map: map,
query: {
select: "col1",
from: "xxxxxxxxxxxxxxxxxxxxxxxxxx"
},
options: {
styleId: 3,
templateId: 3
}
});
I already looked for ways to get this problem solved and I found this sample http://jsbin.com/efobeg/13/edit.
EDIT:
Here's the code that I am currently working on.
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 3,
center: new google.maps.LatLng(0,0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'col7',
from: '10NhYAiDivSpUnjvNsOwZVTEPV-RjhRGmyEOGjs4'
},
map: map,
suppressInfoWindows: true,
options: {
styleId: 2,
templateId: 3
}
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(layer, 'click', function(e) {
var name = e.row['restaurantname'].value;
var cuisine = e.row['cuisine'].value;
var address = e.row['full_address'].value;
var rating = e.row['rating'].value;
if (rating != "") {
if (rating == 1) {
rating = "http://exrx.net/test_weewok2/1.png";
} else if (rating == 2) {
rating = "http://exrx.net/test_weewok2/2.png";
} else if (rating == 3) {
rating = "http://exrx.net/test_weewok2/3.png";
} else if (rating == 4) {
rating = "http://exrx.net/test_weewok2/4.png";
} else {
rating = "http://exrx.net/test_weewok2/5.png";
}
} else {
rating = "http://exrx.net/test_weewok2/1.png";
}
var review = e.row['review'].value;
if (review == "") {
review = "No one has reviewed this place.";
}
var contentString = [
'<div class="tabs">',
'<ul>',
'<li><span>Overview</span></li>',
'<li><span>Review</span></li>',
'<li><span>Images</span></li>',
'</ul>',
'<div id="tab-1">',
'<b>' + name + '</b><img src="' + rating + '" /><br>',
'<font size=1><b>' + address + '</b></font></center>',
'<p align=justify><font size=1>' + cuisine + '</font>',
'</p>',
'</div>',
'<div id="tab-2">',
'<p align=justify><i>"' + review + '"</i></p>',
'</div>',
'<div id="tab-3">',
'<p>Images will be displayed here.</p>',
'</div>',
'</div>'
].join('');
infowindow.setContent(contentString);
infowindow.setPosition(e.latLng);
infowindow.open(map);
$(".tabs").tabs({ selected: 0 });
});
}
Screenshot:
Related
For some reason, Markercluster is doubling the markers in a group. For example, when I click on a group I see four individual markers instead of two. The names are duplicated too. I looked through other posts but am still confused by this. Thanks!
<script>
var mapData = <?php echo wp_json_encode($mapData); ?>;
var map = L.map('map').setView([40, 0], 2);
var markers = new L.MarkerClusterGroup();
L.mapbox.accessToken = 'myToken';
var geocoder = L.mapbox.geocoder('mapbox.places');
for ( var i = 0; i < mapData.length; i++ )
{
geocoder.query(mapData[i].city, showLoc);
}
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=myToken', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(map);
function showLoc (err, data) {
var city = data.results.query.join(' ');
for ( var i = 0; i < mapData.length; i++ )
{
if ( mapData[i].city.toLowerCase() === city ) {
var marker = L.marker(new L.LatLng(data.latlng[0], data.latlng[1]), {
icon: L.mapbox.marker.icon({'marker-color': 'c70c2b'}),
title: mapData[i].name
});
//new L.Marker([data.latlng[0], data.latlng[1]], 2)
marker.bindPopup("<strong>" + mapData[i].name + "</strong>")
markers.addLayer(marker);
}
}
markers.addTo(map);
}
Think I figured it out. Very simple fix. Had to move var markers = new L.MarkerClusterGroup(); in my showLoc (err, data) function. I think it has to do with declaring it after the map tiles load. Not sure though.
I have two websites which attempt to display a map of bushfires in an area, using the Google Maps javascript api and a GeoJson from the NSW RFS. Both are resposive sites.
The maps seem very twitchy about displaying the actual map background, and in one case I always get a grey background (though markers etc are properly displayed).
This seems to be related to the way the map canvas is sized; if a fixed width and height are set then all is well, but if % are used grey is displayed. In the one case setting width and height in vw (% of viewport width) works, but in the other it does not.
The site that works is http://lansdowne.rfsa.org.au/firemap.php
the one that does not is http://www.upperlansdownehall.org.au/firemap/ - if you zoon out to a larger area ytou will see that markers appear in both maps.
The major difference is that one is Wordpress, with the javascript enqueued with the footer, while the other is imbedded in the html.
I have tried setting the size (width and height) of the map-canvas in js (or that of an enclosing division) using the following code either in the initilize routine or just before the addDomListener(window, 'load', initialize);
var mw = document.getElementById('map-canvasout').offsetWidth;
var mw = document.documentElement.clientWidth * .5;
var mh = mw * .75;
var mhx = mh + "px";
var mapara = document.getElementById('map-canvasout');
mapara.style.height= mhx;
I would be very grateful for any ideas, as I am out of them. code for the wordpress scripts encode and js follows:-
add_action('wp_enqueue_scripts', 'ulmh_googlemaps', 105);
function ulmh_googlemaps(){
if (is_page('32') || is_page('233')) {
wp_register_script( 'gmap', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyBAlriyR-tmJU4jrd0z9nmWEmw4XSS0nC0',true);
wp_register_script( 'ulmh_gmap', plugins_url( 'firemap.js', __FILE__ ),true);
wp_enqueue_script('gmap');
wp_enqueue_script('ulmh_gmap');
}
}
function initialize() {
var lat = -31.71 ;
var lng = 152.47;
var zom = 12;
var nam = "Upper Lansdowne";
var mapOptions = {
center: { lat: lat, lng: lng},
zoom: zom
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
map.data.loadGeoJson('http://www.upperlansdownehall.org.au/wp-content/uploads/majorIncidents.json');
map.data.setStyle(function(feature) {
var IconBase = 'http://www.rfs.nsw.gov.au/_designs/geojson/fires-near-me/images/';
var image = {
url: IconBase + 'watch-and-act.png',
size: new google.maps.Size(27, 27),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(14, 13)
};
var ctg = feature.getProperty('category');
switch (ctg) {
case "Emergency Warning": image.url = IconBase + 'emergency-warning.png'; break;
case "Watch and Act": image.url = IconBase + 'watch-and-act.png'; break;
case "Advice": image.url = IconBase + 'advice.png'; break;
default: image.url = IconBase + 'not-applicable.png';
}
return {
icon: image
};
});
var infowindow = new google.maps.InfoWindow();
map.data.addListener('click', function(event) {
var ef = event.feature;
var myHTML = '<b>'+ef.getProperty("title") + '</b></br>' + ef.getProperty("description");
infowindow.setContent("<div style='width:250px;'>"+myHTML+"</div>");
infowindow.setPosition(event.latLng);
infowindow.setOptions({pixelOffset: new google.maps.Size(0,0)});
infowindow.open(map);
});
nam = 'Fire Map of the ' + nam + ' Area';
lat = Math.round(lat*10000)/10000;
lng = Math.round(lng*10000)/10000;
google.maps.event.addListener(map, 'idle', function() { // 'bounds_changed'
google.maps.event.trigger(map, 'resize');
var mapbnd = map.getBounds();
var nbrfre = 0;
map.data.forEach(function(feature) {
var geo = feature.getGeometry();
if (geo.getType() == 'Point') {
var LatLng = geo.get();
if (mapbnd.contains(LatLng)) {
nbrfre = nbrfre +1;
}
} else if (geo.getType() == 'GeometryCollection') {
var LatLng = geo.getAt(0).get();
console.log(LatLng);
if (mapbnd.contains(LatLng)) {
nbrfre = nbrfre +1;
}
}
});
var fretxt = ' (No Fires)';
if (nbrfre == 1) {
fretxt = ' (1 Fire)';
} else if (nbrfre > 1) {
fretxt = ' (' + nbrfre + ' Fires)';
}
var ctr = map.getCenter();
clt = Math.round(ctr.lat()*10000)/10000;
cln = Math.round(ctr.lng()*10000)/10000;
if ((clt != lat) || (cln != lng) ||(zom != map.getZoom())) {
nn = 'General Fire Map';
} else {
nn = nam;
}
var pstttl = document.getElementsByClassName("posttitle");
pstttl[0].innerHTML = nn + fretxt;
if (nbrfre != 0) {
pstttl[0].style.backgroundColor='red';
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Well it seems my unconscious is better at this than the rest of me, as I woke up this morning with a partial answer. One site was using the experimental version of Google Maps (by default) while the other specified v=3 and therefore got the release version.
Of course that raises the question of what is happening at Googles end, but I’ll chase that up with them.
Thanks to anyone who looked at the question.
I should have on my hands what is proper working JS and an xml file...I'm simply trying to take advantage of the huge database of locations that has been offered up as free for everyone to use - located # http://www.craftbeer.com/breweries/brewery-locator/find-a-us-brewery
I'm tried using their maps.js and xml file...but all I end up with is a blank maps screen...
Here is the Javascript...
/*********************************************
**Google Maps Custom API work**
This code can be reused on any site to display a local map of breweries from our local iMis dump, as well as pull in beermapping.
Hey! Don't forget to include API in functions.php! Function is conditionally initialized in footer.php
*/
//Set up variables to create marker
var gmarkers = [];
var mapMarkers = [];
var geocoder = new google.maps.Geocoder();
var icon = 'http://www.craftbeer.com/wp-content/uploads/marker.png';
//Initialize Map
function view_map(xml_file, latitude, longitude, varZoom) {
console.log('view map');
map = new google.maps.Map(document.getElementById("map_canvas"), { //Create the map, Set Default Zoom level and type
center: new google.maps.LatLng(latitude, longitude),
zoom: varZoom,
mapTypeId: 'roadmap',
panControl: true,
zoomControl: true,
mapTypeControl: false,
scaleControl: true,
streetViewControl: false,
overviewMapControl: false
});
//-- Listeners --//
google.maps.event.addListener(map, 'center_changed', function() {
console.log('center changed');
//clearMarkers();
});
google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
//this part runs when the mapobject is created and rendered
console.log("loaded");
$("#loading-screen").fadeOut(250, function(){});
$("#loading-icon").fadeOut();
//google.maps.event.addListenerOnce(map, 'tilesloaded', function(){ });
});
//console.log(xml_file);
var download_file = xml_file; //this variable is passed in so we can re-use this script
//Pull in the XML feed
downloadUrl(download_file, function(data) {
console.log("downloading xml");
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//Loop through all markers in the XML file
for (var i = 0; i < markers.length; i++) {
var state = markers[i].getAttribute("state");
var x = markers[i].getAttribute("lat");
var y = markers[i].getAttribute("lng");
if ( state != 'PR' && state != 'VI' && state != 'GU' && x != "" ){
//console.log(state);
var ids = parseFloat(markers[i].getAttribute("id"));
var z = new google.maps.LatLng(x,y,i);
//console.log(x);
var _id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("company");
var address = markers[i].getAttribute("address");
var city = markers[i].getAttribute("city");
var zip = markers[i].getAttribute("zip");
var phone = markers[i].getAttribute("phone");
var url = markers[i].getAttribute("url");
var brewery_type = markers[i].getAttribute("type");
var member_type = '';
var member_type = markers[i].getAttribute("member_type");
var offer = markers[i].getAttribute("offer");
var html = "<div class='bubble_content'><strong>" + name + "</strong><br />";
html += address + "<br/>" + city + ", " + state + " " + zip;
if(url) html += "<br /><br /><a href='http://" + url + "' target='_blank'>Visit Web Site</a></div>";
//var marker = createMarker(ids, z, title, contentstring);
var marker = new google.maps.Marker({
position: z,
map: map,
title: name,
icon: icon,
html: html,
zindex: i
});
//Add a listener for every icon click
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(this.html);
infowindow.open(map,this);
//map.setZoom(10);
//map.setCenter(this.getPosition());
console.log(this);
});
gmarkers[ids] = marker;
mapMarkers.push(marker);
if( x && y ){
//console.log(ids);
var infowindow = new google.maps.InfoWindow({content: html});
}
/* google.maps.event.addListener(marker, 'click', function() {
console.log('marker clicked');
});
*/
//bounds.extend(z);
//map.fitBounds(bounds);
}//end check for US states only!
} //end for loop
var mcOptions = {gridSize: 60, maxZoom: 9};
var markerCluster = new MarkerClusterer(map, mapMarkers, mcOptions); //this is the function that groups the icons into markers
});
} //End full function to create map
/*
* FUNCTION
*
* click to bring up one icon when clicked from the list.
*/
function myclick(i){
console.log('clicked a title ' + i);
smoothScroll("#primary");
var lat = parseFloat(gmarkers[i].position.k);
var lng = parseFloat(gmarkers[i].position.B);
console.log(lat);
map.setCenter({lat: lat, lng: lng});
map.setZoom(13);
google.maps.event.trigger(gmarkers[i], 'click');
};
function createMarker(ids, z, title, contentstring){
console.log('createMarker');
var marker = new google.maps.Marker({
position: z,
map: map,
title: title,
html: contentstring,
icon: 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(this.html);
infowindow.open(map,marker);
});
gmarkers[ids] = marker;
//console.log(gmarkers[ids]);
};
/*
* FUNCTION findAddress()
*
* given an adress string, zoom the map to the proper state
*/
function findAddress(position) {
//Let's determind if we have a state (address) or LatLng
var addressStr = $("#state_select li.active").data('state-id');
if (addressStr != 'Select a State') address = "US State of "+addressStr;
if(position) {
var lat = parseFloat(position['latitude']);
var lng = parseFloat(position['longitude']);
var latlng = new google.maps.LatLng(lat, lng);
//console.log(latlng);
}
//Now let's geocode - two different cases
if (geocoder && position) { //If LatLng
//console.log('near me');
geocoder.geocode( { 'location': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
map.fitBounds(results[0].geometry.viewport); //resize map to fit.
map.setZoom(13);
}
} else {
alert("No results found");
}
}
});
} else if (geocoder && address!="") { //If State
//console.log('by state');
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
map.fitBounds(results[0].geometry.viewport); //resize map to fit.
map.setZoom(6);
}
} else {
alert("No results found");
}
}
});
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
And here is the link to the xml file....
http://www.straighttothepint.com/wp-content/uploads/wp-google-maps/Google_Map_APIs.xml
I've spent days doing google searches and testing different sections of code to at least get a basic google map to show up via the xml file markers...but to no avail - Any help would be tremendously appreciated!!
~Cheers
EDIT:
Everything worked as expected once I included the following script inline on the page prior to calling the maps.js file. Thanks everyone!
<script>
$(document).ready(function(){
var latitude = 39.300299;
var longitude = -97.382812;
view_map('./uploads/your_xml_file.xml', latitude,longitude,4);
//scripts to handle mapping are in js/mylibs/map.js.php
});
</script>
Looking at the html and the code you provided above I constructed a fiddle for you:
http://jsfiddle.net/loanburger/qafsex5x/
I added two markers in an xml string at the top in the fiddle.
I basically parse the xml doing this:
var markers = $(xml).find("marker");
Its then simply the same for loop you had:
for (var i = 0; i < markers.length; i++)
{
...
}
The fiddle will show you the markers.
I have to admit, I wing it a bit with Google Maps API. A lot of copy and pasting and basic edits. This code works really well unless a street view image is not available. What is the easiest way to detect no image and hid the pano div? Or the other way round, display it if there is an image:
function googleMap() {
var geocoder = new google.maps.Geocoder();
if (geocoder) {
alert('<?php echo $phoneDirectory->Address; ?>');
geocoder.geocode({ 'address': '<?php echo $phoneDirectory->Address; ?>' }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var googleLat = results[0].geometry.location.lat();
var googleLong = results[0].geometry.location.lng();
//alert(googleLat + ", " + googleLong);
var fenway = new google.maps.LatLng(googleLat,googleLong);
var mapOptions = {
center: fenway,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById('map_canvas'), mapOptions);
var panoramaOptions = {
position: fenway,
pov: {
heading: 0,
pitch: 0
}
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'),panoramaOptions);
map.setStreetView(panorama);
// **** ADDED TO GET WORKING!!! *****
var client = new google.maps.StreetViewService();
client.getPanoramaByLocation(fenway, 50, function(result, status) {
if (status == "ZERO_RESULTS") {
// Hide street view div
$('#pano').css("display", "none");
}
});
googleMapLoaded = true;
}
else {
alert('No results found: ' + status);
}
});
}
}
Check this
If there are no nearby panoramas the result is ZERO_RESULTS
Long time reader/ first time poster here, with a question I suspect will be easy to answer but help me out no end.
I simply want to i) retrieve the user's location, ii) display an icon at this location, and iii) Have a button labelled 'Find Me' that pans the map to this location.
I have i) and ii) working, but although I have other buttons that pan to a particular location, this one doesn't seem to work:
var viewportHeight = $(window).height();
var mapHeight = viewportHeight - 93;
var map;
var union = new google.maps.LatLng(53.806828, -1.555999);
var userLocation;
var userIcon = 'userIcon.png';
var parkinson = new google.maps.LatLng(53.808, -1.553);
var unionDescription = '<div id="content">' + '<div id="siteNotice">' + '</div>' + '<h2 id="firstHeading" class="firstHeading">Your Union</h2>' + '<div id="bodyContent">' + '<p>Heres a bit about us</p>' + '</div>' + '</div>';
//Try and get the user's location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
$('#map_canvas').gmap('addMarker', {
'position': userLocation,
'bounds': false,
'icon': userIcon
});
});
};
//initialise the map
$(function () {
$('#map_canvas').gmap({
'center': union,
'zoom': 16,
'mapTypeId': google.maps.MapTypeId.ROADMAP,
'styles': campusStyles,
'minZoom': 15,
'maxZoom': 17
}).bind('init', function (ev, map) {
$('#map_canvas').gmap('addMarker', {
'position': parkinson,
'bounds': false
}).click(function () {
$('#map_canvas').gmap('openInfoWindow', {
'content': 'Hello World!'
}, this);
});
$('#map_canvas').gmap('addMarker', {
'position': union,
'bounds': true
}).click(function () {
$('#map_canvas').gmap('openInfoWindow', {
'content': unionDescription
}, this);
});
$('#map_canvas').height(mapHeight);
google.maps.event.trigger(map, 'resize');
$('#unionButton').click(function () {
map.panTo(union);
});
$('#findMe').click(function () {
map.panTo(userLocation);
});
$('#map_canvas').height(mapHeight);
});
});
Thing I'm actually working on here: http://jdp.org.uk/tests/mapstest4.html
I don't know why but my navigator geolocation is not working, so I just bypassed that requirement and hard-coded a user LatLng. What worked for me was cutting and pasting the whole block if(navigator.geolocaton) to directly below the block with the line $('#unionButton').click(function(){map.panTo(union);});. It appears that map was not yet defined where you had the geolocation code.
From my testing, smooth panning only happens when the current position is close to the target. http://jsfiddle.net/EejRt/
I have:
$('#map_canvas').height(mapHeight);
google.maps.event.trigger(map, 'resize');
$('#unionButton').click(function(){map.panTo(union);});
$('#map_canvas').height(mapHeight);
//if (navigator.geolocation) {
// navigator.geolocation.getCurrentPosition(function(position) {
// var userLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var userLocation = new google.maps.LatLng(53.8018,-1.553);
$('#map_canvas').gmap('addMarker', {'position': userLocation, 'bounds': false, 'icon' : userIcon });
$('#findMe').click(function(){map.panTo(userLocation)});
// });
// };