Toggle custom labels on and off in Google Maps V3 - google-maps

Added some labels to my Google Map (v3), ideally I'd like two things:
1) To be able to switch them on and off (as when zoomed out the labels become cluttered)
2) To be able to change the textsize of the label depending up the mapzoom.
I added the labels like so, info being read in from some nested arrays:
for (x = 0; x < areadata.length; x++){//Start Label Loop
labelObjects[x] = new MapLabel({
text: areadata [x][0],
position: new google.maps.LatLng(areadata [x][2], areadata [x][1]),
map: mymap,
fontSize: 16,
align: 'center'
});
labelObjects[x].set('position', new google.maps.LatLng(areadata [x][2], areadata [x][1]));
}
I'm using the maplabel-compiled.js from http://google-maps-utility-library-v3.googlecode.com/svn/trunk/maplabel/examples/maplabel.html - with one change however. mapPane.appendChild has been amended to floatPane.appendChild - this brings all labels in front of any Polygons I have on the map.
This works just fine, the problem comes when I try to control the labels, I've tried interacting with the first label in the array like so with no joy:
labelObjects[0].setVisible(false);
labelObjects[0].set('visible', false);
labelObjects[0].set('fontSize', 48);
Anyone had similar issues? Thanks for reading.

be sure that labelObjects is accessible in the scope where try to toggle the mapLabel
there is no method setVisible for a MapLabel
setting a visible-property of a MapLabel will not have any effect. To show/hide the MapLabel set the map-property of the MapLabel to either a google.maps.Map-instance(mymap) or null
var areadata = [
['label#1', 1, 1],
['label#2', 2, 2]
],
labelObjects = [],
mymap;
function init() {
var myLatlng = new google.maps.LatLng(1.5, 1.5),
myOptions = {
zoom: 7,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
mymap = new google.maps.Map(document.getElementById('map'), myOptions);
for (x = 0; x < areadata.length; x++) { //Start Label Loop
labelObjects[x] = new MapLabel({
text: areadata[x][0],
position: new google.maps.LatLng(areadata[x][2], areadata[x][1]),
map: mymap,
fontSize: 16,
align: 'center'
});
labelObjects[x].set('position', new google.maps.LatLng(areadata[x][2], areadata[x][1]));
}
mymap.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('toggle'));
}
google.maps.event.addDomListener(window, 'load', init);
body,
html,
#map {
margin: 0;
padding: 0;
height: 100%;
}
#toggle {
padding: 1px 6px;
border: 1px solid rgba(0, 0, 0, 0.15);
box-shadow: 0 1px 4px -1px rgba(0, 0, 0, 0.3);
border-radius:2px;
background: #fff;
cursor: pointer;
margin:4px;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/js-map-label#1.0.1/src/maplabel.js"></script>
<div id="map"></div>
<a id="toggle" onclick="labelObjects[0].setMap((labelObjects[0].getMap())?null:mymap)">toggle label#1</a>

Related

Dragging shapes from a palette onto a Konvajs stage

On the Konvajs chat stream someone recently asked for an example of drag-and-drop from a palette onto an HTML5 canvas fronted by the Konvajs library. There were no ready examples and I was curious about how to achieve it.
I answered the question in a codepen but decided to post here for (my own) future reference. See my answer below.
Here is my solution using jquery UI draggable & droppables. Konvajs requires jquery so the use of jquery UI is only a small step further. The palette is a set of small canvas elements with one shape drawn per draggable item. The palette can be housed on any html element and does not need to be attached to the main stage in any way.
// Set up the canvas to catch the dragged shapes
var s1 = new Konva.Stage({container: 'container1', width: 500, height: 200});
// add a layer to host the 'dropped' shapes.
var layer1 = new Konva.Layer({draggable: false});
s1.add(layer1);
// set up the palette of draggable shapes - 5 sample shapes.
var palletteEle = $('#pallette');
var d, ps, l, c;
for (var i = 0; i<5; i = i + 1){
// make a div to hold the shape
d = $('<div id="shape' + i + '" class="draggable">Shape</div>')
palletteEle.append(d)
// make a mini stage to hold the shape
ps = new Konva.Stage({container: 'shape' + i, width: 50, height: 50});
// make a layer to hold the shape
l = new Konva.Layer();
// add layer to palette
ps.add(l);
// make a shape - red circles for example
c = new Konva.Circle({x: 24, y: 24, radius: 22, fill: 'red', stroke: 'black'})
l.add(c);
ps.draw();
}
// make a crosshair to give some idea of the drop location
var cross = new Konva.Line({points: [10, 0, 10, 20, 10, 10, 0, 10, 20, 10],
stroke: 'gold',
strokeWidth: 1,
lineCap: 'round',
lineJoin: 'round'})
layer1.add(cross);
//s1.draw();
// make the main stage a drop target
$('#container1').addClass('droppable');
// function to move the cross hairs
function moveCross(x, y){
cross.x(x);
y = y - $('#container1').offset().top;
cross.y(y < 0 ? 0 : y);
s1.draw();
}
// draggable setup. Movecross used to move the crosshairs. More work needed but shows the way.
$( ".draggable" ).draggable({
zIndex: 100,
helper: "clone",
opacity: 0.35,
drag: function( event, ui ) {moveCross(ui.offset.left , ui.offset.top + $(this).offset().top)}
});
// set up the droppable
$( ".droppable" ).droppable({
drop: function( event, ui ) {
dropShape(ui.position.left, ui.position.top)
}
});
// Function to create a new shape when we drop something dragged from the palette
function dropShape() {
var c1 = new Konva.Circle({x: cross.x(), y: cross.y(), radius: 22, fill: 'red', stroke: 'black'});
layer1.add(c1);
cross.x(0); cross.y(0);
cross.moveToTop(); // move the cross to the top to stop going bahind previously dropped shapes.
s1.draw();
}
p
{
padding: 4px;
}
#container1
{
display: inline-block;
width: 500px;
height: 200px;
background-color: silver;
overflow: hidden;
}
#pallette
{
height: 52px; width: 500px;
border: 1px solid #666;
margin-bottom: 10px;
z-index: 10;
}
.draggable
{
width:50px;
height: 50px;
display: inline-block;
border: 1px solid #666;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdn.rawgit.com/konvajs/konva/1.6.5/konva.min.js"></script>
<p>Drag a red circle from the pallette and drop it on the grey canvas.
</p>
<div id='pallette'></div>
<div id='container1'></div>
I tried Vanquished Wombat's solution, it was a great example. But ultimately I wanted my palette to be separate from Konva. So I modified that original snippet to work with Html5 drag & drop, without any jQuery. See the snippet below. You can drag stars & circles from the palette into the Konva canvas. Currently you have to drop onto another shape, but you can modify it easily to drop anywhere on the canvas. I'm using text for the palette items and a custom image for the drag object just for fun. But you can just use an img instead of using the setDragImage code.
const CUSTOM_DATA_TYPE = 'text/x-node-type';
// Set up the canvas to catch the dragged shapes
var s1 = new Konva.Stage({
container: 'container1',
width: 500,
height: 200
});
// add a layer to host the 'dropped' shapes.
var layer1 = new Konva.Layer({
draggable: false
});
s1.add(layer1);
for (let t = 0; t < 10; t++) {
let rect = document.getElementById('container1').getBoundingClientRect();
let x = Math.floor(Math.random() * rect.width);
let y = Math.floor(Math.random() * rect.height);
let type = Math.floor(Math.random() * 100) % 2 == 0 ? 'circle' : 'star';
dropShape(x, y, type);
}
// Function to create a new shape when we drop something dragged from the palette
function dropShape(x, y, type) {
var shape;
if (type == 'circle') {
shape = new Konva.Circle({
x: x,
y: y,
radius: 22,
fill: 'blue',
stroke: 'black'
});
} else {
shape = new Konva.Star({
x: x,
y: y,
numPoints: 5,
innerRadius: 10,
outerRadius: 20,
fill: 'purple',
stroke: 'black'
});
}
layer1.add(shape);
s1.draw();
}
function cursorToCanvasPos(e) {
let clientRect = document.getElementById('container1').getBoundingClientRect();
let pointerPosition = {
x: e.clientX - clientRect.x,
y: e.clientY - clientRect.y,
};
return pointerPosition;
}
function getHoveredShape(e) {
let pointerPosition = cursorToCanvasPos(e);
return s1.getIntersection(pointerPosition);
}
function onDragStart(e, type) {
// Do this or other things can mess with your drag
e.stopPropagation();
e.dataTransfer.setData(CUSTOM_DATA_TYPE, type);
e.dataTransfer.effectAllowed = "all";
var dragIcon = document.createElement('img');
dragIcon.src = 'https://placehold.it/100x100';
dragIcon.width = 100;
e.dataTransfer.setDragImage(dragIcon, 150, 150);
}
function onDragOver(e) {
// Might break if you don't have this
e.stopPropagation();
// Breaks for sure if you don't have this
e.preventDefault();
let thing = getHoveredShape(e);
if (thing) {
e.dataTransfer.dropEffect = "move";
// Just fire off a custom even if you want to, this does nothing in this example.
thing.fire('htmlDragOver');
} else {
e.dataTransfer.dropEffect = "none";
}
}
function onDrop(e) {
e.stopPropagation();
let type = e.dataTransfer.getData(CUSTOM_DATA_TYPE);
let pos = cursorToCanvasPos(e);
dropShape(pos.x, pos.y, type);
}
p {
padding: 4px;
}
#container1 {
display: inline-block;
width: 500px;
height: 200px;
background-color: silver;
overflow: hidden;
}
#palette {
height: 52px;
width: 500px;
border: 1px solid #666;
margin-bottom: 10px;
z-index: 10;
}
#palette span {
width: 50px;
height: 25px;
display: inline-block;
border: 1px solid #666;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdn.rawgit.com/konvajs/konva/1.6.5/konva.min.js"></script>
<p>Drag circle/star from the palette onto an existing shape on the canvas below.
</p>
<div id='palette'>
<!-- Pre-load this image so it'll be used for our drag -->
<img src="https://placehold.it/100x100" style="display: none">
<span draggable="true" ondragstart="onDragStart(event, 'circle')">circle</span>
<span draggable="true" ondragstart="onDragStart(event, 'star')">star</span>
</div>
<div id='container1' ondragover="onDragOver(event)" ondrop="onDrop(event)"></div>

how to add my location button to google map

i would like to add my location button to my map like the real google map does.
ihave tried some plugins but they didnt had location button, what should i do?
here is one plugin that i used:
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var GeoMarker = new GeolocationMarker(map);
For web browsers you can use the html5 built in geolocation to get your location: You can follow this doc: https://developers.google.com/maps/documentation/javascript/examples/map-geolocation
But first set a default location in case the browser doesn't support Geolocation
var myLocation = {lat: -34.397, lng: 150.644};
After that in your init function you can get your location like this:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
myLocation.lat = position.coords.latitude;
myLocation.lng = position.coords.longitude;
map.setCenter(myLocation);
}, function() {
handleLocationError(true, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, map.getCenter());
}
Set your location's coordinates as default center of the map
map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: myLocation,
mapTypeId: 'roadmap'
});
Then just call this function if you want to go back to your location
function goToMyLocation() {
map.setCenter(myLocation);
}
Check this working example: https://jsbin.com/ricebu/edit?html,css,js,output
Here is the code snippet as well
var map;
var btnLocation = document.getElementById("btn-location");
var myLocation = {
lat: -34.397,
lng: 150.644
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: myLocation,
mapTypeId: 'roadmap'
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
myLocation.lat = position.coords.latitude;
myLocation.lng = position.coords.longitude;
// I just added a marker for you to verify your location
var marker = new google.maps.Marker({
position: myLocation,
map: map
});
map.setCenter(myLocation);
}, function() {
handleLocationError(true, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
console.log(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
btnLocation.addEventListener('click', function() {
goToMyLocation();
});
function goToMyLocation() {
map.setCenter(myLocation);
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#btn-location {
position: absolute;
right: 20px;
top: 20px;
z-index: 1;
padding: 20px;
border: none;
border-radius: 4px;
background-color: rgba(255, 255, 255, 0.8);
transition: 0.5s;
}
#btn-location:hover {
background-color: rgba(0, 0, 0, 1);
color: white;
cursor: pointer;
}
<html>
<head>
<title>Location</title>
</head>
<body>
<button id="btn-location">Go to my Location</button>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCKQX3cyZ7pVKmBwE8wiowivW9qH62AVk8&callback=initMap"></script>
</body>
</html>
var btnLocation = document.getElementById("btn-location");
var myLocation = {
lat: -34.397,
lng: 150.644
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: myLocation,
mapTypeId: 'roadmap'
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
myLocation.lat = position.coords.latitude;
myLocation.lng = position.coords.longitude;
// I just added a marker for you to verify your location
var marker = new google.maps.Marker({
position: myLocation,
map: map
});
map.setCenter(myLocation);
}, function() {
handleLocationError(true, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
console.log(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
btnLocation.addEventListener('click', function() {
goToMyLocation();
});
function goToMyLocation() {
map.setCenter(myLocation);
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#btn-location {
position: absolute;
right: 20px;
top: 20px;
z-index: 1;
padding: 20px;
border: none;
border-radius: 4px;
background-color: rgba(255, 255, 255, 0.8);
transition: 0.5s;
}
#btn-location:hover {
background-color: rgba(0, 0, 0, 1);
color: white;
cursor: pointer;
}
<html>
<head>
<title>Location</title>
</head>
<body>
<button id="btn-location">Go to my Location</button>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCKQX3cyZ7pVKmBwE8wiowivW9qH62AVk8&callback=initMap"></script>
</body>
</html>
You can also consider using https://www.npmjs.com/package/google-maps-current-location
It adds the typical button to the map, it handles the geolocation, and it also adds the blue circle surrounding the marker.
Hope it helps :)

How add circle Shape in Google maps custom icon?

I have problem with custom images on map.
For example:
My icons generated this way, and icon contains image:
var ic = { //icon
url: icon, // url
scaledSize: new google.maps.Size(30, 30), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0), // anchor
//define the shape
//define the shape
shape:{coords:[17,17,18],type:'circle'},
//set optimized to false otherwise the marker will be rendered via canvas
//and is not accessible via CSS
optimized:false,
title: 'spot'
};
var marker = new google.maps.Marker({
map: map, title: name , position: latlngset, icon: ic
});
I want make my icons like css 50% radius (circle shape).
How I can do it?
Related question: JS Maps v3: custom marker with user profile picture
Using code from there, and changing the border-radius to 50%, gives me a circular icon with the image in the circle.
proof of concept fiddle
//adapted from http://gmaps-samples-v3.googlecode.com/svn/trunk/overlayview/custommarker.html
function CustomMarker(latlng, map, imageSrc) {
this.latlng_ = latlng;
this.imageSrc = imageSrc;
// Once the LatLng and text are set, add the overlay to the map. This will
// trigger a call to panes_changed which should in turn call draw.
this.setMap(map);
}
CustomMarker.prototype = new google.maps.OverlayView();
CustomMarker.prototype.draw = function() {
// Check if the div has been created.
var div = this.div_;
if (!div) {
// Create a overlay text DIV
div = this.div_ = document.createElement('div');
// Create the DIV representing our CustomMarker
div.className = "customMarker"
var img = document.createElement("img");
img.src = this.imageSrc;
div.appendChild(img);
var me = this;
google.maps.event.addDomListener(div, "click", function(event) {
google.maps.event.trigger(me, "click");
});
// Then add the overlay to the DOM
var panes = this.getPanes();
panes.overlayImage.appendChild(div);
}
// Position the overlay
var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
if (point) {
div.style.left = point.x + 'px';
div.style.top = point.y + 'px';
}
};
CustomMarker.prototype.remove = function() {
// Check if the overlay was on the map and needs to be removed.
if (this.div_) {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
CustomMarker.prototype.getPosition = function() {
return this.latlng_;
};
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 17,
center: new google.maps.LatLng(37.77088429547992, -122.4135623872337),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var data = [{
profileImage: "http://www.gravatar.com/avatar/d735414fa8687e8874783702f6c96fa6?s=90&d=identicon&r=PG",
pos: [37.77085, -122.41356],
}, {
profileImage: "http://placekitten.com/90/90",
pos: [37.77220, -122.41555],
}]
for (var i = 0; i < data.length; i++) {
new CustomMarker(new google.maps.LatLng(data[i].pos[0], data[i].pos[1]), map, data[i].profileImage)
}
.customMarker {
position: absolute;
cursor: pointer;
background: #424242;
width: 100px;
height: 100px;
/* -width/2 */
margin-left: -50px;
/* -height + arrow */
margin-top: -110px;
border-radius: 50%;
padding: 0px;
}
.customMarker:after {
content: "";
position: absolute;
bottom: -10px;
left: 40px;
border-width: 10px 10px 0;
border-style: solid;
border-color: #424242 transparent;
display: block;
width: 0;
}
.customMarker img {
width: 90px;
height: 90px;
margin: 5px;
border-radius: 50%;
}
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map" style="width: 640pxpx; height: 480px;">map div</div>
After some google, I found this simple and easiest way for making a marker circle shape. Anyone can also customize it easily.
Here is a sample code -
<script>
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 15,
center: { lat: 23.8178689, lng: 90.4213642 },
});
const your_img_url = "https://avatars.githubusercontent.com/u/22879378?v=4";
var icon = {
url: your_img_url + '#custom_marker', // url + image selector for css
scaledSize: new google.maps.Size(32, 32), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
const marker = new google.maps.Marker({
position: { lat: 23.8178689, lng: 90.4213642 },
map,
icon: icon,
});
}
</script>
And your CSS style are -
<style>
img[src$="#custom_marker"]{
border: 2px solid #900 !important;
border-radius:50%;
}
</style>
Output:
If you want to make a circular marker just check the documentation This is faster and more lightweight.
Otherwise, just make your actual icon into a circular shape.

Map loads incorrectly with Angular-Leaflet-Directive

Good morning!
I have a web application, where I use a leafletjs map (http://tombatossals.github.io/angular-leaflet-directive/#!/) and openstreetmap as tile.
The map works perfectly, I can interact in any way (add markers, create layers, zoom ..), however, when I access the page where the map is, it does not load correctly, according to the printscreen below:
It resets when I resize the window or open and close the console.
Font:
View:
<div class="col-md-12">
<div class="box_whiteframe_map">
<leaflet ng-init="vm.buscaEnderecoClientesEmpresas()" center="vm.center" defaults="vm.defaults" markers="vm.markers" width="100%" height="480px"></leaflet>
</div>
CSS/SASS:
.box_whiteframe_map {
background-color: #fff;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2), 0 1px 1px 0 rgba(0, 0, 0, .14), 0 2px 1px -1px rgba(0, 0, 0, .12);
color: #000;
margin: 0;
clear: both;
}
Controller:
/* MAP */
vm.markers = new Array();
vm.buscaEnderecoClientesEmpresas = function() {
vm.items = loadSaas(Cookies.get('crm_o2_hash')); // carregar saas id
vm.items.then(function(items) { // ler array de retorno
vm.saasid = items;
var dados = {
'saasid': vm.saasid
}
relatoriosService.carregarEnderecoClientesEmpresas(dados).then(function(response) {
if (response.data != 'null') {
vm.enderecoClientesEmpresas = response.data;
angular.forEach(vm.enderecoClientesEmpresas, function(value, key) {
if (value.tipo == 'p'){
var icon = 'user';
} else {
var icon = 'cog';
}
vm.markers.push({
group: value.cidade,
lat: value.lat_lng.lat,
lng: value.lat_lng.lng,
message: value.nome,
icon: {
type: 'awesomeMarker',
icon: icon,
markerColor: 'blue'
},
label: {
options: {
noHide: true
}
}
});
});
} else {
vm.enderecoClientesEmpresas = '';
}
}, function(error) {
console.log('Erro findSemEmail: ', error);
});
});
}
angular.extend(vm, { // EXTEND THE PROPERTIES OF MAP (MARKERS, INITIAL LOCATION..)
center: { // INITIAL LOCATION .
lat: -22.952419,
lng: -43.211667,
zoom: 4
},
defaults: {
tileLayer: "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
zoomControlPosition: 'topright',
tileLayerOptions: {
opacity: 0.9,
detectRetina: true,
reuseTiles: true,
attribution: '© OpenStreetMap | &copy Funil PRÓ',
},
scrollWheelZoom: true,
minZoom: 3,
worldCopyJump: true
}
});
/* MAP FINAL */
Any help?
[]'s
You need to refresh the map:
leafletData.getMap().then(function(map) {
setTimeout(function() {
map.invalidateSize();
map._resetView(map.getCenter(), map.getZoom(), true);
}, 200);
});
In additionally, you need to inject leafletData to controller.
You need to add leaflet css
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.css">

Google Map marker text

I have found this icon: http://chart.apis.google.com/chart?cht=mm&chs=60x102&chco=ffffff,70a3c1,70a3c1&ext=.png
I'm wondering if it's possible to place text on this icon. Basically what I'm looking for is an icon with a dynamic color and text. A simple PHP script that dynamically generates an icon based on a images and text would also be great.
You can create image from png (using PHP GD )
$yourimage = imagecreatefrompng($originalImage);
Add in your html page this tag
<img src="test_icon.php?text=yourtext">
and the add the text you need
this way using test_icon.php
test_icon.php
<?php
header("Content-type: image/png");
$yourOrigImage = "group_icon.png";
if(file_exists($yourOrigImage)) {
$newImage = imagecreatefrompng($yourOrigImage);
imagesavealpha($newImage, true); // this for keep the png's transparency important
if(!$newImage) {
die("im is null");
}
$black = imagecolorallocate($newImage, 0, 0, 0);
$width = 36; // the width of the image
$height = 36; // the height of the image
$font = 4; // font size
$text = $_GET['text']; // text
$leftTextPos = 4;
$outputImage = "group_icon_".$text.".png";
imagestring($newImage, $font, $leftTextPos, 9, $text, $black);
imagepng($newImage, $outputImage, 0);
imagedestroy($newImage);
}
?>
Two options:
The third party MarkerWithLabel library.
fiddle
code snippet:
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new MarkerWithLabel({
position: map.getCenter(),
map: map,
icon: "http://chart.apis.google.com/chart?cht=mm&chs=60x102&chco=ffffff,70a3c1,70a3c1&ext=.png",
labelContent: "A",
labelAnchor: new google.maps.Point(15, 90),
labelClass: "labels", // the CSS class for the label
labelInBackground: false
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
.labels {
color: black;
font-family: "Lucida Grande", "Arial", sans-serif;
font-size: 30px;
text-align: center;
width: 30px;
white-space: nowrap;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerwithlabel/src/markerwithlabel.js"></script>
<div id="map_canvas"></div>
Add a label to the native google.maps.Marker
fiddle
code snippet::
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
icon: "http://chart.apis.google.com/chart?cht=mm&chs=60x102&chco=ffffff,70a3c1,70a3c1&ext=.png",
label: "A"
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>