Keep Getting this.callInitHooks error (Leaflet) - javascript

I'm trying to add markers and a search bar to my leaflet choropleth map. However, I keep running into an error that tells me: Uncaught TypeError: this.callInitHooks is not a function. It comes from my leaflet.js file, and am unsure how to fix it. Most of my error seems to come from the leaflet links I've copied into my body before my script, or because of me trying to add a search bar or markets onto my map. I pasted my code below:
<html>
<head>
<title>How to make a choropleth map with Leaflet.js</title>
<meta charset="utf-8">
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.0/dist/leaflet.css" />
<link rel="stylesheet" href="leaflet-search.css" />
<script src="censustracts.js"></script>
<style type="text/css">
html, body, #map{
height: 100%;
padding: 0;
margin: 0;
}
.info {
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255,255,255,0.8);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
border-radius: 5px;
}
.info h4 {
margin: 0 0 5px;
color: #777;
}
.legend {
line-height: 18px;
color: #555;
}
.legend i {
width: 18px;
height: 18px;
float: left;
margin-right: 8px;
opacity: 0.7;
}
</style>
</head>
<body>
<div id="map"></map>
<script src="https://unpkg.com/leaflet#1.3.0/dist/leaflet.js"></script>
<script src="leaflet-search.js"></script>
<script type="text/javascript">
var map = L.map('map').setView([37.8, -96], 4);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {attribution: 'OSM'})
.addTo(map);
L.geoJson(statesData).addTo(map);
L.geoJson(statesData).addTo(map);
function getColor(d) {
return d > 1000 ? '#800026' :
d > 500 ? '#BD0026' :
d > 200 ? '#E31A1C' :
d > 100 ? '#FC4E2A' :
d > 50 ? '#FD8D3C' :
d > 20 ? '#FEB24C' :
d > 10 ? '#FED976' :
'#FFEDA0';
}
function style(feature) {
return {
fillColor: getColor(feature.properties.density),
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7
};
}
L.geoJson(statesData, {style: style}).addTo(map);
///Functionality
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 5,
color: '#666',
dashArray: '',
fillOpacity: 0.7
});
info.update(layer.feature.properties);
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
}
function resetHighlight(e) {
geojson.resetStyle(e.target);
info.update();
}
function zoomToFeature(e) {
map.fitBounds(e.target.getBounds());
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature
});
}
geojson = L.geoJson(statesData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
//Add info
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
this.update();
return this._div;
};
// method that we will use to update the control based on feature properties passed
info.update = function (props) {
this._div.innerHTML = '<h4>US Population Density</h4>' + (props ?
'<b>' + props.name + '</b><br />' + props.density + ' people / mi<sup>2</sup>'
: 'Hover over a state');
};
info.addTo(map);
//Add Legend
var legend = L.control({position: 'bottomright'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend'),
grades = [0, 10, 20, 50, 100, 200, 500, 1000],
labels = [];
// loop through our density intervals and generate a label with a colored square for each interval
for (var i = 0; i < grades.length; i++) {
div.innerHTML +=
'<i style="background:' + getColor(grades[i] + 1) + '"></i> ' +
grades[i] + (grades[i + 1] ? '–' + grades[i + 1] + '<br>' : '+');
}
return div;
};
legend.addTo(map);
///Bind Popups
var data = [
{"loc":[32,-86], "title":"aquamarine"},
{"loc":[41.575730,13.002411], "title":"black"},
{"loc":[41.807149,13.162994], "title":"blue"},
{"loc":[41.507149,13.172994], "title":"chocolate"},
{"loc":[41.847149,14.132994], "title":"coral"},
{"loc":[41.219190,13.062145], "title":"cyan"},
{"loc":[41.344190,13.242145], "title":"darkblue"},
{"loc":[41.679190,13.122145], "title":"Darkred"},
{"loc":[41.329190,13.192145], "title":"Darkgray"},
{"loc":[41.379290,13.122545], "title":"dodgerblue"},
{"loc":[41.409190,13.362145], "title":"gray"},
{"loc":[41.794008,12.583884], "title":"green"},
{"loc":[41.805008,12.982884], "title":"greenyellow"},
{"loc":[41.536175,13.273590], "title":"red"},
{"loc":[41.516175,13.373590], "title":"rosybrown"},
{"loc":[41.506175,13.273590], "title":"royalblue"},
{"loc":[41.836175,13.673590], "title":"salmon"},
{"loc":[41.796175,13.570590], "title":"seagreen"},
{"loc":[41.436175,13.573590], "title":"seashell"},
{"loc":[41.336175,13.973590], "title":"silver"},
{"loc":[41.236175,13.273590], "title":"skyblue"},
{"loc":[41.546175,13.473590], "title":"yellow"},
{"loc":[41.239190,13.032145], "title":"white"}
];
var markersLayer = new L.LayerGroup(); //layer contain searched elements
map.addLayer(markersLayer);
var controlSearch = L.Control.Search({
position:'topright',
layer: markersLayer,
initial: false,
zoom: 12,
marker: false
});
map.addControl( controlSearch );
for(i in data) {
var title = data[i].title, //value searched
loc = data[i].loc, //position found
marker = new L.Marker(new L.latLng(loc), {title: title} );//se property searched
marker.bindPopup('title: '+ title );
markersLayer.addLayer(marker);
}
</script>
</body>
</html>

Don't use new with lowercase function:
marker = new L.Marker(new L.latLng(loc), {title: title} );
Use new L.LatLng(loc) or L.latLng(loc) without new

Related

Leaflet map • trouble porting code from old website

I've copied over code from an exciting website (https://romonysetra.no/tomtevelger/) to new website build (WP Divi). But I have no luck getting the code to work on the new site.https://romonysetra.no/divi/tomtevelger/
Any tips on what is wrong or what it not working on the new website build is greatly appreciated. Thanks!
<div id="mapid"></div>
<script type="text/javascript" src="https://romonysetra.no/tomteData.js"></script>
<script type="text/javascript">
var mymap = L.map('mapid', { zoomSnap:0,zoomDelta: 0.5}).setView([61.55794889870435, 12.220130837034901], 16);
L.tileLayer('https://opencache.statkart.no/gatekeeper/gk/gk.open_gmaps?layers=topo4&zoom={z}&x={x}&y={y}', {
attribution: 'Kartverket'}).addTo(mymap);
var info = L.control();
info.onAdd = function (mymap) {
this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
this.update();
return this._div;
};
// method that we will use to update the control based on feature properties passed
info.update = function (props) {
this._div.innerHTML = '<h4>Informasjon</h4>' + (props ?
'<b>' + props.name + '</b><br/><br/>' + props.pris + '<br/>' + props.status + '<br/>' + props.areal
: 'Vis tomtedata');
};
info.addTo(mymap);
function getColor(d) {
return d > 1000 ? '#800026' :
d > 75 ? '#636363' :
d > 65 ? '#3182bd' :
d > 35 ? '#276897' :
d > 25 ? '#de2d26' :
d > 15 ? '#feb24c' :
d > 5 ? '#31a354' :
'#efedf5';
}
function style(feature) {
return {
weight: 2,
opacity: 1,
color: 'black',
dashArray: '3',
fillOpacity: 0.5,
fillColor: getColor(feature.properties.farge)
};
}
var geojsonTomt;
var geojsonVei;
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 2,
color: '#f0f0f0',
dashArray: '',
fillOpacity: 0.7
});
layer.bringToFront();
info.update(layer.feature.properties);
}
function resetHighlight(e) {
geojsonTomt.resetStyle(e.target);
info.update();
}
function zoomToFeature(e) {
mymap.fitBounds(e.target.getBounds());
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature
});
}
geojsonTomt = L.geoJson(tomteData, {
style: style,
onEachFeature: onEachFeature
}).addTo(mymap);
geojsonVei = L.geoJson(veiData, {
style: style
}).addTo(mymap);
</script>
Found it. This was missing form the head of the page.
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.5.1/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet#1.5.1/dist/leaflet.js"></script>
<style>
#mapid { width: 1200px; height: 800px; }.info {
padding: 6px 8px;
font: 16px/18px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255,255,255,0.8);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
border-radius: 5px;
}
.info h4 {
margin: 0 0 5px;
color: #777;
}
.text-labels {
position: absolute;
font-size: 2em;
font-weight: 700;
/* Use color, background, set margins for offset, etc */
}
</style>

Remove background map Leaflet

I'm using Leaflet to make a cloropleth map over Europe. I would like to remove the map so that just the cloropleth layer is visible (background white).
I've tried to use different versions of map.removeLayer but I haven't been able to make a change without removing all layers.
I've also tried to alter .leaflet-container in the css.
Any ideas on how to remove the background map and keep the colored layer over the countries?
<script type="text/javascript" src="europe_countries.js"></script>
<script type="text/javascript">
var map = L.map('map').setView([50.888571, 10.413779], 3);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.light'
}).addTo(map);
// control that shows state info on hover
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
};
info.update = function (props) {
this._div.innerHTML = '<h4>US Population Density</h4>' + (props ?
'<b>' + props.name + '</b><br />' + props.density + ' people / mi<sup>2</sup>'
: 'Hover over a state');
};
info.addTo(map);
// get color depending on population density value
function getColor(d) {
return d > 1000 ? '#800026' :
d > 500 ? '#BD0026' :
d > 200 ? '#E31A1C' :
d > 100 ? '#FC4E2A' :
d > 50 ? '#FD8D3C' :
d > 20 ? '#FEB24C' :
d > 10 ? '#FED976' :
'#FFEDA0';
}
function style(feature) {
return {
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7,
fillColor: getColor(feature.properties.density)
};
}
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 2,
color: '#666',
dashArray: '',
fillOpacity: 0.7
});
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
info.update(layer.feature.properties);
}
var geojson;
function resetHighlight(e) {
geojson.resetStyle(e.target);
info.update();
}
function zoomToFeature(e) {
map.fitBounds(e.target.getBounds());
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature
});
}
geojson = L.geoJson(statesData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
map.attributionControl.addAttribution('Population data © US Census Bureau');
var legend = L.control({position: 'bottomright'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend'),
grades = [0, 10, 20, 50, 100, 200, 500, 1000],
labels = [],
from, to;
for (var i = 0; i < grades.length; i++) {
from = grades[i];
to = grades[i + 1];
labels.push(
'<i style="background:' + getColor(from + 1) + '"></i> ' +
from + (to ? '–' + to : '+'));
}
div.innerHTML = labels.join('<br>');
return div;
};
legend.addTo(map);
function drawMap(tile){
map.eachLayer(function (layer) {
map.removeLayer(layer);
});
map.addLayer(tile);
}
</script>
CSS:
<style>
html, body {
height: 100%;
margin: 0;
}
#map {
width: 600px;
height: 400px;
}
</style>
<style>#map { width: 800px; height: 500px;}
.info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: white; box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .info h4 { margin: 0 0 5px; color: #777; }
.legend { text-align: left; line-height: 18px; color: #555; } .legend i { width: 18px; height: 18px; float: left; margin-right: 8px; opacity: 0.7; }
</style>
If i'm understanding the question correct, Using the example you added in the comments, I believe you can hide .leaflet-tile-container?
.leaflet-tile-container {
display: none;
}

Disable scroll zoom on mapbox

I'm trying to disable scroll zoom on a mapbox map, but it is not working. Can anyone let me know what's wrong with my code? The error I get is "Uncaught TypeError: Cannot read property 'disable' of undefined"
<script>
L.mapbox.accessToken = 'pk.token';
var map = L.mapbox.map('map', 'mapbox.streets', {
legendControl: {
position: 'topright'
}
})
.setView([56.3, 11.5], 7);
var popup = new L.Popup({ autoPan: false });
// statesData comes from the 'us-states.js' script included above
var statesLayer = L.geoJson(statesData, {
style: getStyle,
onEachFeature: onEachFeature
}).addTo(map);
function getStyle(feature) {
return {
weight: 2,
opacity: 0.1,
color: 'black',
fillOpacity: 0.7,
fillColor: getColor(feature.properties.density)
};
}
// get color depending on population density value
function getColor(d) {
return d > 1000 ? '#512b00' :
d > 500 ? '#8E4C01' :
d > 200 ? '#cc4c02' :
d > 100 ? '#ec7014' :
d > 50 ? '#fe9929' :
d > 20 ? '#fec44f' :
d > 10 ? '#fee391' :
d > 5 ? '#fff7bc' :
'#ffffe5';
}
function onEachFeature(feature, layer) {
layer.on({
mousemove: mousemove,
mouseout: mouseout,
click: zoomToFeature
});
}
var closeTooltip;
function mousemove(e) {
var layer = e.target;
popup.setLatLng(e.latlng);
popup.setContent('<div class="marker-title">' + layer.feature.properties.name + '</div>' +
layer.feature.properties.density + ' feriehuse');
if (!popup._map) popup.openOn(map);
window.clearTimeout(closeTooltip);
// highlight feature
layer.setStyle({
weight: 3,
opacity: 0.3,
fillOpacity: 0.9
});
if (!L.Browser.ie && !L.Browser.opera) {
layer.bringToFront();
}
}
function mouseout(e) {
statesLayer.resetStyle(e.target);
closeTooltip = window.setTimeout(function() {
map.closePopup();
}, 100);
}
function zoomToFeature(e) {
map.fitBounds(e.target.getBounds());
}
map.legendControl.addLegend(getLegendHTML());
function getLegendHTML() {
var grades = [0, 5, 10, 20, 50, 100, 200, 500, 1000],
labels = [],
from, to;
for (var i = 0; i < grades.length; i++) {
from = grades[i];
to = grades[i + 1];
labels.push(
'<li><span class="swatch" style="background:' + getColor(from + 1) + '"></span> ' +
from + (to ? '–' + to : '+')) + '</li>';
}
return '<span>Antal feriehuse</span><ul>' + labels.join('') + '</ul>';
}
// disable map zoom when using scroll
map.scrollZoom.disable();
</script>
This is a mapbox.js / leaflet map, not mapbox-gl-js, so the difference is in Leaflet the scroll zoom control is called scrollWheelZoom not scrollZoom. If you replace the last line of your script with the following it should work. http://jsfiddle.net/x5j669zj/
if (map.scrollWheelZoom) {
map.scrollWheelZoom.disable();
}

get coordinates of drawn feature in OpenLayers

I'm trying to create an online map using OpenLayers 3.
I'm brand new to using OpenLayers, and all I'm trying to do is to get the coordinates of the points, lines, polygons that I drew on the map. I'm aware that there is a featuresadded parameter available, but I'm not able to implement it correctly.
Can anybody point me in the right direction how to get the coordinates of a drawn feature (either in an alert() or console.log)?
Thanks a ton!!
here's my code:
<html>
<head>
<script src="http://openlayers.org/en/v3.3.0/build/ol.js" type="text/javascript"></script>
<link rel="stylesheet" href="ol.css" type="text/css">
<style type="text/css">
body {
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: small;
}
#map {
clear: both;
position: relative;
border: 1px solid black;
}
#wrapper {
width: 337px;
height: 50px;
}
#location {
float: right;
font-family: Arial, Verdana, sans-serif;
font-size: 12px;
color: #483D8B;
background-color: white;
}
#nodelist{
font-family: Arial, Verdana, sans-serif;
font-size: 14px;
color: #000000;
font-style: normal;
background-color: white;
}
</style>
<script type="text/javascript">
var map;
var draw;
var transformed_coordinate;
var vector;
function init() {
var view = new ol.View({
center: ol.proj.transform([13.1929, 55.718],'EPSG:4326', 'EPSG:3857'),
zoom: 12
});
var myZoom = new ol.control.Zoom();
var myZoomSlider = new ol.control.ZoomSlider();
var zoomToExtentControl = new ol.control.ZoomToExtent({
extent: [1453297.22,7490484.81,1483872.03,7513415.91]
});
var myScaleLine = new ol.control.ScaleLine()
var neighborhood = new ol.source.ImageWMS({
url: 'http://localhost:8090/geoserver/project/wms',
params: {'LAYERS': 'project:Neighborhood'}
});
var roads = new ol.source.ImageWMS({
url: 'http://localhost:8090/geoserver/project/wms',
params: {'LAYERS': 'project:Roads_all'}
});
var source = new ol.source.Vector({wrapX: false});
vector = new ol.layer.Vector({
source: source,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(0, 255, 0, 0.5)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
})
});
var layers = [
new ol.layer.Image({
source: neighborhood
}),
new ol.layer.Image({
source: roads
}),
vector
]
map = new ol.Map({
layers: layers,
target: 'map',
view: view
});
map.addControl(myZoom);
map.addControl(myZoomSlider);
map.addControl(zoomToExtentControl);
map.addControl(myScaleLine);
map.on('singleclick', function(evt){
var coord = evt.coordinate;
transformed_coordinate = ol.proj.transform(coord, "EPSG:3857", "EPSG:4326");
//console.log(transformed_coordinate);
})
function onFeaturesAdded(event){
var bounds = event.features[0].geometry.getBounds();
var answer = "bottom: " + bounds.bottom + "\n";
answer += "left: " + bounds.left + "\n";
answer += "right: " + bounds.right + "\n";
answer += "top: " + bounds.top + "\n";
alert(answer);
}
var typeSelect = document.getElementById('type');
function addInteraction() {
var value = typeSelect.value;
if (value !== 'None') {
var geometryFunction, maxPoints;
if (value === 'Square') {
value = 'Circle';
geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
} else if (value === 'Box') {
value = 'LineString';
maxPoints = 2;
geometryFunction = function(coordinates, geometry) {
if (!geometry) {
geometry = new ol.geom.Polygon(null);
}
var start = coordinates[0];
var end = coordinates[1];
geometry.setCoordinates([
[start, [start[0], end[1]], end, [end[0], start[1]], start]
]);
return geometry;
};
}
draw = new ol.interaction.Draw({
source: source,
type: /** #type {ol.geom.GeometryType} */ (value),
geometryFunction: geometryFunction,
maxPoints: maxPoints
});
map.addInteraction(draw);
}
}
/**
* Let user change the geometry type.
* #param {Event} e Change event.
*/
typeSelect.onchange = function(e) {
map.removeInteraction(draw);
addInteraction();
};
addInteraction();
} //end init
</script>
</head>
<body onload="init()">
<div id="map" style="width: 800px; height: 600px"></div>
<form class="form-inline">
<label>Geometry type </label>
<select id="type">
<option value="None">None</option>
<option value="Point">Point</option>
<option value="LineString">LineString</option>
<option value="Polygon">Polygon</option>
</select>
</form>
</body>
</html>
Register a listener on ol.source.Vector and wait until the drawn feature is added:
source.on('addfeature', function(evt){
var feature = evt.feature;
var coords = feature.getGeometry().getCoordinates();
});
Use drawend event
drawend (ol.interaction.DrawEvent) - Triggered upon feature draw ends
Ex:
this.draw = new ol.interaction.Draw();
this.draw.on('drawend', function(evt){
//in evt you will get ol.feature
// from ol.feature get the geometry and than get coordinates
});
Let me know if I am wrong.

Range Rings in Google Maps V3

I have a script that was written a long time ago and not by me that I have updated from V2 to V3 and I am trying to draw range rings from a centered LatLng point. This worked in V2 but it is not working in V3 and I can't figure out why as I know some of the code is depreciated but not sure what it needs to be replaced with.
//Function to draw circles
function doDrawCircle(circleUnits, center, circleRadius, liColor, liWidth, liOpa, fillColor, fillOpa, opts, radials){
var bounds = new google.maps.LatLngBounds();
var circlePoints = Array();
with (Math) {
if (circleUnits == 'KM') {
var d = circleRadius/6378.8; // radians
}
else { //miles
var d = circleRadius/3963.189; // radians
}
var lat1 = (PI/180)* center.lat(); // radians
var lng1 = (PI/180)* center.lng(); // radians
for (var a = 0 ; a < 361 ; a++ ) {
var tc = (PI/180)*a;
var y = asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc));
var dlng = atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(y));
var x = ((lng1-dlng+PI) % (2*PI)) - PI ; // MOD function
var point = new google.maps.LatLng(parseFloat(y*(180/PI)),parseFloat(x*(180/PI)));
circlePoints.push(point);
bounds.extend(point);
if(a==0){
var offset = new google.maps.Size(-5,0); // Added the offset - mile markers look a bit better
var label = new ELabel(point, circleRadius, "style1", offset, 40);
map.addOverlay(label);
}
if (((a==0) || (a==45) || (a==90) || (a==135) || (a==180) || (a==225) || (a==270) || (a==315)) && radials) {
//if (((a==0) || (a==45) || (a==90) || (a==135) || (a==180)) && radials) {
var pline = new google.maps.Polyline([center,point] , liColor, liWidth, liOpa);
map.addOverlay(pline);
}
}
var poly = new google.maps.Polygon(circlePoints, liColor, liWidth, liOpa, fillColor, fillOpa, opts);
map.addOverlay(poly); // Add a target circle to the map
map.setZoom(map.getBoundsZoomLevel(bounds)); // This sets the map bounds to be as big as the target circles, comment out if you don't want it
}
}
Then I have this within the initialize() function for the map.
// You can add circles, or change other parameters
// radials should be set to true for the maximum distance if you want radials
// doDrawCircle(circleUnits, center, circleRadius, lineColor, lineWidth, lineOpacity, fillColor, fillOpacity, opts, radials)
doDrawCircle('MI',llCenter, 62, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI',llCenter, 124, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI',llCenter, 187, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI',llCenter, 249, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI',llCenter, 312, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI',llCenter, 374, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
// doDrawCircle('MI',llCenter, 374, lcolor, 1, .7, '#00FF00', 0, { clickable: false }, true); // This would add the radials
This is what it is suppose to look like. This is from the working V2 map.
V2 EXAMPLE
Link to full code
FULL MAP CODE
First thing you'll need to do is get the newest version of elabel.js for google maps V3 here:
https://github.com/erunyon/ELabel/blob/master/elabel.js
Then, the good news is you don't need all of that complicated math and stuff which you have going on in your doDrawCircle function. You can now make use of google.maps.Circle as well as the geometry library which must be included via the google maps script tag's url parameters using a 'libraries=geometry' parameter so we can get the text label placement position starting point via google.maps.geometry.spherical.computeOffset. And then I've included a little tweeking of the text placement below to look a bit more tidy.
Test case:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Circles</title>
<style type="text/css">
.style1 {
/* used for range numbers on rings */
color: #FFF;
font-size: 10px;
text-shadow: 2px 2px 2px #000;
font-weight: bold;
font-family: verdana, helvetica, arial, sans-serif;
background-color:black;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=geometry"></script>
<!-- elabel.js for google maps V3 from here: https://github.com/erunyon/ELabel/blob/master/elabel.js -->
<script src="elabel.js"></script>
<script>
function initialize() {
var i, meters, options, labelLocation, textLength, textXcenter, label,
//note I declared the actual font pixel size in .style1 css rule
//just to help with visualizing the way I'm positioning the label texts
textPixelSize = 10,
//will need to invert textYcenter as well as textXcenter to negative numbers later
textYcenter = (textPixelSize / 2) + 2, //2px tweak for 'y' position, approximation
mapOptions = {
zoom: 6,
center: new google.maps.LatLng(32.8297,-96.6486),
mapTypeId: google.maps.MapTypeId.HYBRID
},
ranges = [62, 124, 187, 249, 312, 374], //circle radii in miles
circles = [],
labels = [],
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
for (i = 0; i < ranges.length; i++) {
//convert miles to meters:
meters = ranges[i] / 0.00062137;
options = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 1,
fillOpacity: 0,
map: map,
center: mapOptions.center,
radius: meters
};
circles.push(new google.maps.Circle(options));//ta-da! easy circles in V3
//labelLocation will be a google.maps.LatLng object
labelLocation = google.maps.geometry.spherical.computeOffset(mapOptions.center, meters, 0);
textLength = (''+ranges[i]).length;
textXcenter = (textLength * textPixelSize) / 2; //approximation
label = new ELabel({
latlng: labelLocation,
label: ranges[i],
classname: 'style1',
offset: new google.maps.Size(-textXcenter, -textYcenter),//negative will move left and up
opacity: 100,
overlap: true,
clicktarget: false
});
label.setMap(map);
labels.push(label);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas" style="width:780px; height:600px; margin:10px auto;"></div>
</body>
</html>
EDIT:
Here is revised version which allows to toggle visibility of the rings via the 'Range' button. Also removed all the text label positioning adjustment math and replaced with using style classes for different length texts instead (makes it easier to just use em units in the styles if desired). Added LabelCircle constructor for easier encapsulation and simultaneous control of circles & labels.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Circles</title>
<style type="text/css">
.style1 {
/*used for range numbers on rings*/
color: #FFF;
font-size: .6em;
text-shadow: 2px 2px 2px #000;
font-weight: bold;
font-family: verdana, helvetica, arial, sans-serif;
background-color:black;
margin-top: -0.5em;
}
.d2 { /*two-digit numbers on rings*/
margin-left: -1em;
}
.d3 { /*three-digit numbers on rings*/
margin-left: -1.5em;
}
/*direct copy of your existing .button style rule*/
.button{
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
text-align: center;
position: relative;
font-family: Arial, sans-serif;
font-size: 13px;
font-weight:bold;
box-shadow: rgba(0, 0, 0, 0.4) 0 2px 4px;
-moz-box-shadow: rgba(0, 0, 0, 0.4) 0 2px 4px;
-webkit-box-shadow: rgba(0, 0, 0, 0.4) 0 2px 4px;
color: #000;
border: 1px solid #717B87;
background-color: #fff;
margin: 5px;
padding: 1px 6px;
overflow: hidden;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=geometry"></script>
<!-- elabel.js for google maps V3 from here: https://github.com/erunyon/ELabel/blob/master/elabel.js -->
<script src="elabel.js"></script>
<script>
function LabelCircle(options) {
this.circle = new google.maps.Circle(options.circleOptions);
this.label = new ELabel(options.labelOptions);
this.label.setMap(options.circleOptions.map);
this.isVisible = true;
}
LabelCircle.prototype.setVisible = function (bool) {
var method = (bool) ? 'show' : 'hide';
this.circle.setVisible(bool);
this.label[method]();
this.isVisible = bool;
};
//a direct copy of your existing function
function buttonControl(options) {
var control = document.createElement('DIV');
control.innerHTML = options.name;
control.className = 'button';
control.index = 1;
// Add the control to the map
options.gmap.controls[options.position].push(control);
google.maps.event.addDomListener(control, 'click', options.action);
return control;
}
function initialize() {
var i, meters, options, labelLocation, textLength, label,
mapOptions = {
zoom: 6,
center: new google.maps.LatLng(32.8297,-96.6486),
mapTypeId: google.maps.MapTypeId.HYBRID
},
ranges = [62, 124, 187, 249, 312, 374], //circle radii in miles
labelCircles = [],
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
for (i = 0; i < ranges.length; i++) {
//convert miles to meters:
meters = ranges[i] / 0.00062137;
//labelLocation will be a google.maps.LatLng object
labelLocation = google.maps.geometry.spherical.computeOffset(mapOptions.center, meters, 0);
//we'll use textLength below to add a class to the label
textLength = (''+ranges[i]).length;
options = {
circleOptions: {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 1,
fillColor: 'transparent',
fillOpacity: 0,
map: map,
center: mapOptions.center,
radius: meters
},
labelOptions: {
latlng: labelLocation,
label: ranges[i],
classname: 'style1 d' + textLength,
//offset: //no longer needed, using style classes
opacity: 100,
overlap: true,
clicktarget: false
}
};
labelCircles.push(new LabelCircle(options));
}
var rangeOptions = {
gmap: map,
name: 'Range',
position: google.maps.ControlPosition.TOP_RIGHT,
action: function(){
for (var tmp, i = 0; i < labelCircles.length; i++) {
tmp = labelCircles[i];
tmp.setVisible(!tmp.isVisible);
}
}
};
var rangeButton = buttonControl(rangeOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas" style="width:780px; height:600px; margin:10px auto;"></div>
</body>
</html>

Categories