I am using Google Maps API. I want to assign colors to some countries.
To do that, i have to get each country boundaries to be able to draw polygon. So, i'm using FusionTables. For every countries, I do FusionTables query to get the layer and then set the map. Here what i have done.
var countryArray = new Array();
var nodeArray = new Array();
var companyArray = new Array();
var locationsArray = new Array();
function plotMarker() {
var rootMarker = locationsArray[companyArray.indexOf(rootCompany)];
var latlng = new google.maps.LatLng(0, 0);
var myStyle = [
{
featureType: "all",
elementType: "labels",
stylers: [
{
visibility: "off" }
]
}
];
map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeControlOptions: {
mapTypeIds: ['mystyle', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.TERRAIN]
},
center: latlng,
zoom: 2,
mapTypeId: 'mystyle'
});
map.mapTypes.set('mystyle', new google.maps.StyledMapType(myStyle, { name: 'My Style' }));
for (var i = 0; i < locationsArray.length; i++) {
if (locationsArray[i] != undefined) {
var latitude = locationsArray[i].lat() + verDiff;
var longitude = locationsArray[i].lng() + horDiff;
var newLatlng = new google.maps.LatLng(latitude, longitude);
var ftoptions = {
query: {
from: '419167',
select: 'kml_4326',
where: "sovereignt = '"+countryArray[i]+"'"
},
suppressInfoWindows:true,
styles: [
{
polygonOptions: {
fillColor:'#0040FF',
fillOpacity:0.7
}
}
]
};
var layer = new google.maps.FusionTablesLayer(ftoptions);
layer.setMap(map);
}
}
}
But, why does the style only work for the first country? I wonder if the queries are not successfully performed for all countries or just there's something wrong with the style? Any helps would be appreciated.
A map can only have 1 styled FusionTablesLayer, the styles of the other layers will be ignored.
Create a single FusionTablesLayer and select multiple sovereignt's via a IN()-condition
Related
I'm trying to add a marker to my google map within my HTML project. The map centres on the exact coordinates I like and is perfect except the marker I've added doesn't show up at all. I've followed the documentation but to no success.
var google;
function init() {
var myLatlng = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var mapOptions = {
// How zoomed in you want the map to start at (always required)
zoom: 7,
// The latitude and longitude to center the map (always required)
center: myLatlng,
// How you would like to style the map.
scrollwheel: false,
styles: [
{
"featureType": "administrative.country",
"elementType": "geometry",
"stylers": [
{
"visibility": "simplified"
},
{
"hue": "#ff0000"
}
]
}
]
};
I'm using a div with id="map" seen below
var mapElement = document.getElementById('map');
var map = new google.maps.Map(mapElement, mapOptions);
var addresses = ['New York'];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map,
title: 'NY'
});
});
}
}
google.maps.event.addDomListener(window, 'load', init);
You have to add your API key.
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false&key=ADD_YOUR_API_KEY', null, function (data) {
Check this out!
https://developers.google.com/maps/documentation/geocoding/intro#GeocodingResponses
How do I toggle the visibility of a subset of markers in Google Maps API?
I have two sets of marker location data. Want to add a button to toggle visibility of each set independently.
Full code below for convenience. I have a button code in the header.
<button onclick="toggleMELocations()">Toggle ME Locations</button>`
The button is showing up, but clicking does not yield the expected result (ME locations disappearing).
The relevant function is "toggleMELocations." I am trying to say that if ME locations are currently visible, make them invisible. And vice versa.
Any help is much appreciated.
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: 40,
lng: -95
},
styles: [{
stylers: [{
saturation: -100
}]
}]
});
setMarkers(map);
}
function toggleMELocations() {
if (MEs) {
for (i in MEs) {
var visibility = (MEs[i].getVisible() == true) ? false : true;
MEs[i].setVisible(visibility);
}
}
}
// MEC locations
var MEs = [
['aaa', 36.07, -75.79],
['bbb', 40.07, -83.79]
];
// CC locations
var Concentras = [
['xxx', 38.01, -75.55],
['yyy', 30.10, -90.3]
];
function setMarkers(map) {
// Adds markers to the map.
for (var i = 0; i < MEs.length; i++) {
var ME = MEs[i];
var marker = new google.maps.Marker({
position: {
lat: ME[1],
lng: ME[2]
},
icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
map: map,
title: ME[0]
});
}
for (var i = 0; i < Concentras.length; i++) {
var Concentra = Concentras[i];
var marker = new google.maps.Marker({
position: {
lat: Concentra[1],
lng: Concentra[2]
},
icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
map: map,
title: Concentra[0]
});
}
}
Firstly getVisible() is not a valid function.
You need to add a global variable defined: var addedMEs = [];
This acts as an array of markers that have been added to the map in the setMarkers method. We change the setMarkers method to include a line which will add a marker object to the array defined above:
for (var i = 0; i < MEs.length; i++) {
var ME = MEs[i];
var marker = new google.maps.Marker({
position: {
lat: ME[1],
lng: ME[2]
},
icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
map: map,
title: ME[0]
});
addedMEs.push(marker);
}
Then we need to remove the getVisible() method as it is invalid. we change this line to:
var bounds = map.getBounds();
var visibility = (bounds.contains(addedMEs[i].position) == true) ? false : true;
addedMEs[i].setVisible(visibility);
And it works. :]
Here is the JSFiddle to try: https://jsfiddle.net/cmjcs5eL/13/
I'm not able to zoom to a particular area/location in Google maps which has multiple Map Pointers. At present it automatically centers the map covering all locations. But what I need is to zoom to a particular location upon opening the webpage. Here is my code,
<script>
jQuery(function ($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "//maps.googleapis.com/maps/api/js?key=AIzaSyA157quXbUlHHgm4wJJxzD49MivKgPSil8&sensor=false&callback=initialize";
document.body.appendChild(script);
});
function initialize() {
locations = <?php echo json_encode($sl_select_obj) ?>;
markerdata = JSON.parse('<?php echo json_encode($locations_data) ?>');
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap',
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers''
// $info='';
var markers = locations;
<?php
$total = count($locations_data);
$markerinfo = '';
$c = 0;
foreach ($locations_data as $key => $info):
if ($c != $total):
$markerinfo .="['<div class=\"info_content\"><h2>" . $info['loctitle'] . "</h2><h3>" . $info['site'] . "</h3><h3>View Full Office Details</h3></div>'],";
else:
$markerinfo .="['<div class=\"info_content\"><h2>" . $info['loctitle'] . "</h2><h3>" . $info['site'] . "</h3><h3>View Full Office Details</h3></div>']";
endif;
$c++;
endforeach;
?>
// Info Window Content
var infoWindowContent = [<?php echo $markerinfo; ?>]; //markerdata;
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for (i = 0; i < markers.length; i++) {
var position = new google.maps.LatLng(markers[i]["lat"], markers[i]["long"]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i]["address"],
icon: '<?php bloginfo('template_directory'); ?>/images/venue-direct-icon.png'
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {
this.setZoom(7);
google.maps.event.removeListener(boundsListener);
});
map.fitBounds(markerBounds);
}
Try to add the "center" option like this:
var mapOptions = {
center: new google.maps.LatLng(51.5287718, -0.2416803),
mapTypeId: 'roadmap',
zoom: 15,
draggable: map_draggable,
scrollwheel: map_scrollwheel
};
EDIT: To help you this is a code similar that I use in my project: multiple positions, center on the first if only one, else I use google autocenter for all positions.
jQuery( document ).ready( function( $ ) {
if($(window).width()>991){
var map_draggable = true;
var map_scrollwheel = false;
} else {
var map_draggable = false;
var map_scrollwheel = false;
}
var offices = [];
$('#map-google-container')
.find('.hidden')
.each(function(){
offices[offices.length] =
{
"latitude":$(this).attr('latitude'),
"longitude":$(this).attr('longitude'),
"content":$(this).attr('content')
};
});
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(offices[0].latitude, offices[0].longitude),
draggable: map_draggable,
scrollwheel: map_scrollwheel,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
panControl: true
};
var map = new google.maps.Map(document.getElementById('map-google'), mapOptions);
var map_styles = [
{
featureType: "all",
stylers: [
{ hue: "#F69200" },
{ saturation: -50 }
]
},{
featureType: "water",
stylers: [
{ color: "#efefef" }
]
}
];
map.setOptions({styles: map_styles});
var image = '/include/images/marker.png';
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < offices.length; i++)
{
var content = offices[i].content;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(offices[i].latitude, offices[i].longitude),
map: map,
icon: image,
animation: google.maps.Animation.DROP,
title: content
});
bounds.extend(marker.position);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
}
if (offices.length > 1) { map.fitBounds(bounds); }
});
In my project I have to list all the offices and show a unique map with all of them. So in the HTML I put the information of all offices (hidden for the user). In JavaScript I loop through these properties and populate the map.
Hope it helps
Yes, I can able to find the solution, for those who are facing this similar issue may find it helpful,
var map_center_position = new google.maps.LatLng(34.0059657 ,-118.4440441);
bounds.extend(map_center_position);
map.fitBounds(bounds);
Some data is producing Google Heat Maps to display red blocks instead of the Heat Layer. I checked my information but I couldn't find anything wrong, here is my code:
for (i = 0; i < markers.length; i++) {
if (markers[i].lat != " ") {
mar.push(markers[i]);
var weightedLoc = {
location: new google.maps.LatLng(mar[j].lat,mar[j].lon),
weight: mar[j].Intensity
};
heat.push(weightedLoc);
j++;
}
}
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(mar[0].lat, mar[0].lon)
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
var pointArray = new google.maps.MVCArray(heat);
heatmap = new google.maps.visualization.HeatmapLayer({
data: heat
});
heatmap.setMap(map);
My data is in this json format:
[
{"lat":"-0.05487","lon":"-78.45286","Intensity":"1.86"},
{"lat":"-0.09377","lon":"-78.45136","Intensity":"2"},
{"lat":"-0.05489","lon":"-78.45283","Intensity":"0.6"}
]
Thanks!
weight has to be of type number, currently it's a string.
Convert it via :
weight: parseFloat(mar[j].Intensity)
proof of concept fiddle
code snippet:
function initialize() {
var markers = [{
"lat": "-0.05487",
"lon": "-78.45286",
"Intensity": "1.86"
}, {
"lat": "-0.09377",
"lon": "-78.45136",
"Intensity": "2"
}, {
"lat": "-0.05489",
"lon": "-78.45283",
"Intensity": "0.6"
}];
var heat = [];
for (i = 0; i < markers.length; i++) {
if (markers[i].lat != " ") {
// mar.push(markers[i]);
var weightedLoc = {
location: new google.maps.LatLng(markers[i].lat, markers[i].lon),
weight: parseFloat(markers[i].Intensity)
};
heat.push(weightedLoc);
// j++;
}
}
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(markers[0].lat, markers[0].lon)
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
var pointArray = new google.maps.MVCArray(heat);
heatmap = new google.maps.visualization.HeatmapLayer({
data: heat
});
heatmap.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#dvMap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=visualization"></script>
<div id="dvMap"></div>
When I experienced this problem, it was because I was accidentally passing empty strings values into the LatLng constructors.
See below:
for (i = 0; i < coords.length; i++) {
var lat = coords[i]
var long = coords[++i]
points.push(new google.maps.LatLng(lat, long)); //<-- no checks on lat, long
}
// heatmap layer
heatmap = new google.maps.visualization.HeatmapLayer({
data: points,
map: map
});
I discovered that there was a potential for lat or long to be empty, so I made the following change:
if (!lat.isEmpty() && !long.isEmpty()) {
points.push(new google.maps.LatLng(lat, long));
}
If the accepted answer does not solve your problems, check to ensure that all of the points you are passing to the heat map are valid.
I am using the following scripting to load homes for sale on to my Google Map. I like to know if this is possible and if it is -- I need help from a really good Google Map programmer to help add it.
What I Am Look For
If one of the addresses within the left panel cannot be found by Google or is out of boundaries, it still loads the element and address to the left panel -- but in a disabled state by adding a class to that element. Can this be done?
Mapping Boundaries
Here is the boundaries, if the marker is within this area it adds the marker else disables the element. If the with boundaries cannot be done, I will take the option of Google not finding it.
http://www.freemaptools.com/radius-around-point.htm?clat=44.512176171071054&clng=-81.08184814453125&r=96.39586143951128&lc=FFFFFF&lw=1&fc=00FF00
Scripting I Am Using
http://www.raymondcamden.com/demos/2012/dec/1/new4.html
Here Is What I Have So Far
I put together the follow scripting based on the site above, just looking to add the missing location element to this concept.
var map;
var markers = [];
var lastinfowindow;
var locIndex;
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fn, scope) {
for (var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
}
}
var data = [
{address:'123 GODERICH ST GODERICH ONTARIO',title:'123 GODERICH ST'},
{address:'123 KNOWLES LANE KINCARDINE ONTARIO',title:'123 KNOWLES LANE'}
];
function Initialize() {
var latlng = new google.maps.LatLng(44.00, -80.00);
var mapOptions = {
zoom : 8,
center : latlng,
mapTypeId : google.maps.MapTypeId.ROADMAP,
scaleControl : true,
mapTypeControl : false,
navigationControlOptions : {
style : google.maps.NavigationControlStyle.SMALL
},
scrollwheel : false,
minZoom : 7,
maxZoom : 15,
keyboardShortcuts : false,
disableDoubleClickZoom : true,
draggable : true,
backgroundColor : '#FFFFFF'
};
var mapStyles = [{
featureType: 'poi',
stylers: [{
visibility: 'off'
}]
}];
var styledMap = new google.maps.StyledMapType(mapStyles, {name: 'Styled Map'});
map = new google.maps.Map(document.getElementById('map'), mapOptions);
geocoder = new google.maps.Geocoder();
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
icon = new google.maps.MarkerImage('/pointer.png', new google.maps.Size(19, 29), new google.maps.Point(0, 0), new google.maps.Point(8, 29));
data.forEach(function(mapData,idx) {
geocoder.geocode({'address':mapData.address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: mapData.title,
icon: icon
});
var contentHtml = "<div style='width:300px;height:200px'><h3>"+mapData.title+"</h3>"+mapData.address+"</div>";
var infowindow = new google.maps.InfoWindow({
content: contentHtml
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
marker.locid = idx+1;
marker.infowindow = infowindow;
markers[markers.length] = marker;
var sideHtml = '<p class="loc" data-locid="'+marker.locid+'"><b>'+mapData.title+'</b><br/>';
sideHtml += mapData.address + '</p>';
$('#locations').append(sideHtml);
}
});
});
}
window.onload = Initialize;
I am currently in the process of seeing if I can do this and will update along the way. Thanks!!
You need to check if the status of the geocode call is either
ZERO_RESULTS
INVALID_REQUEST
or one of the other status codes in the Maps API, such as
geocoder.geocode({'address':mapData.address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
//handle valid address search
} else if (status === google.maps.GeocoderStatus.INVALID_REQUEST
|| status === google.maps.GeocoderStatus.ZERO_RESULTS) {
//handle no results returned
}
}
If you have a geocode request return one of those statuses, you can add the element to the map, but set the marker to a reduced visibility state or some other option that you prefer. For something like this, look into the MarkerOptions and associated Marker documentation at the link above.