Creating text in the center of a marker - javascript

I've been playing with Google Map API for a few days now and it's pretty straight forward for the most part, but one thing that we need to do, I can't figure out. I've played with the labels as you can see in the example below, but I'm unable to give them to look that I have in the image below. Can someone point me to a reference so I can achieve my requirements?
If your looking for the makerwithlable.js, you can get it from here.. Its where I got it:
https://code.google.com/p/google-maps-utility-library-v3/source/browse/trunk/markerwithlabel/src/markerwithlabel.js?r=288
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script src="markerwithlabel.js" type="text/javascript"></script>
<script>
{
var showOnStartInfoWindows = true;
//create locations..
var arrayAll = [];
var marker = [];
var jax = new google.maps.LatLng(30.318028, -81.674474);
var leesburg = new google.maps.LatLng(28.810750, -81.880056);
var map = null;
arrayAll[0] = {loc: jax, size: 5000, info: "Jacksonville, FL 32204"};
arrayAll[1] = {loc: leesburg, size: 1000, info: "Leesburg, FL"};
//EO create locations..
}
function initialize()
{
//center the map on Jacksonville
var mapProp = {
center:arrayAll[0].loc,
zoom:6,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
//set google's API and pass the DIV by ID.
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var bounds = new google.maps.LatLngBounds(leesburg, jax);
map.fitBounds(bounds);
var maxSize = 0;
for(var i = 0; i < arrayAll.length; i++)
{
if(maxSize<arrayAll[i].size)
maxSize = arrayAll[i].size;
}
for(var i = 0; i < arrayAll.length; i++)
{
var size = Math.round((arrayAll[i].size/maxSize)*100);
//create marker
marker[i] = new google.maps.Marker({
position:arrayAll[i].loc,
map: map,
title: 'Right-Click to zoom all the way in.\nLeft-Click to zoom to a state level.',
draggable: false,
raiseOnDrag: false,
labelAnchor: new google.maps.Point(22, 0),
labelClass: "googleLabel", // the CSS class for the label
labelContent: arrayAll[i].info,
icon: {
path: google.maps.SymbolPath.CIRCLE, //BACKWARD_CLOSED_ARROW
fillOpacity: 0.3,
fillColor: '#0000ff',
strokeOpacity: 1.0,
strokeColor: '#0000ff',
strokeWeight: 1.0,
scale: size, //pixels
}
});
marker[i].setMap(map);
//EO create marker
marker_onclick(marker[i]);
marker_info(marker[i]);
}
}
function marker_onclick(marker) {
google.maps.event.addListener(marker, 'dblclick', function(o) {
map.setZoom(18);
map.setCenter(marker.position);
});
google.maps.event.addListener(marker, 'click', function(o) {
map.setZoom(7);
map.setCenter(marker.position);
});
google.maps.event.addListener(marker, 'rightclick', function(o) {
alert('Could route to different URL:\n' + marker.position);
});
}
function marker_info(marker) {
//create popup notice..
var infowindow = new google.maps.InfoWindow({
content:marker.labelContent
});
if(showOnStartInfoWindows)
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'mouseover', function (o) {
//alert('over');
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function (o) {
//alert('out');
infowindow.close(map, marker);
});
//EO create popup notice..
}
{
google.maps.event.addDomListener(window, 'load', initialize);
}
</script>
</head>
<body>
<div id="googleMap" style="width:640px;height:640px;"></div>
</body>
</html>
Example of what I'm trying to do.

Based on the value of size you may set the style(fontSize,width,height etc.) and the labelAnchor
{
var showOnStartInfoWindows = true;
//create locations..
var arrayAll = [];
var marker = [];
var jax = new google.maps.LatLng(30.318028, -81.674474);
var leesburg = new google.maps.LatLng(28.810750, -81.880056);
var map = null;
arrayAll[0] = {
loc: jax,
size: 5000,
info: "Jacksonville, FL 32204"
};
arrayAll[1] = {
loc: leesburg,
size: 1000,
info: "Leesburg, FL"
};
//EO create locations..
}
function initialize() {
//center the map on Jacksonville
var mapProp = {
center: arrayAll[0].loc,
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//set google's API and pass the DIV by ID.
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var bounds = new google.maps.LatLngBounds(leesburg, jax);
map.fitBounds(bounds);
var maxSize = 0;
for (var i = 0; i < arrayAll.length; i++) {
if (maxSize < arrayAll[i].size)
maxSize = arrayAll[i].size;
}
for (var i = 0; i < arrayAll.length; i++) {
var size = Math.round((arrayAll[i].size / maxSize) * 100);
//create MarkerWithLabel
marker[i] = new MarkerWithLabel({
labelInBackground:false,
position: arrayAll[i].loc,
map: map,
title: 'Right-Click to zoom all the way in.\nLeft-Click to zoom to a state level.',
labelAnchor: new google.maps.Point((size * 1.8) / 2, (size / 3)),
labelClass: "googleLabel", // the CSS class for the label
labelStyle: {
width: (size * 1.8) + 'px',
height: (size / 1.5) + 'px',
lineHeight: (size / 1.5) + 'px',
fontSize: (size / 1.5) + 'px'
},
labelContent: arrayAll[i].size,
icon: {
path: google.maps.SymbolPath.CIRCLE,
fillOpacity: 0.6,
fillColor: 'gold',
strokeOpacity: 1.0,
strokeColor: '#0000ff',
strokeWeight: 1.0,
scale: size, //pixels
}
});
marker[i].setMap(map);
}
}
{
google.maps.event.addDomListener(window, 'load', initialize);
}
html,
body,
#googleMap {
margin: 0;
padding: 0;
height: 100%;
}
.googleLabel {
color: #000;
font-weight: bold;
text-align: center;
}
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerwithlabel/src/markerwithlabel.js" type="text/javascript"></script>
<div id="googleMap"></div>

Related

Google Maps API - custom circle onclick event not firing

I am using Google Maps API and I have implemented custom circle using this SO answer as reference which is working absolutely fine.
Here below is my screenshot what I have done so far.
As you can see above, I am showing my count with Map Icon.
Now I have used infobox as well so when I click on map icon, its opening something like this.
Now the problem which I am facing if I click on my count, its not opening the same infobox which is opening if I click on my icon.
I tried to use below code inside my for loop but its not working for me.
google.maps.event.addListener(ibLabel, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
Here is my full source code what I have done so far.
var locations = chartData;
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 4,
center: new google.maps.LatLng(-27.4756261, 129.3748879),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.setOptions({minZoom: 1, maxZoom: 15});
var marker, i;
var circle;
var latlng;
var myLatLng;
var closeInfoBox = document.getElementById("close-button");
var infowindow = new google.maps.InfoWindow({maxWidth: 350});
var oms = new OverlappingMarkerSpiderfier(map, {
//markersWontMove: true, // we promise not to move any markers, allowing optimizations
// markersWontHide: true, // we promise not to change visibility of any markers, allowing optimizations
// basicFormatEvents: true // allow the library to skip calculating advanced formatting information
});
for (i = 0; i < locations.length; i++) {
var user_id_array = '<?= $user_id_array; ?>';
var image_name = 'ouvar-pin-new.png';
var get_user_id = locations[i][4];
var fill_color_val = '#154ff6';
var latitude = locations[i][1];
var lontitude = locations[i][2];
myLatLng = google.maps.LatLng(latitude, lontitude);
var latlng = new google.maps.LatLng(latitude, lontitude);
if (user_id_array != '')
{
var data = JSON.parse(user_id_array);
image_name = data[get_user_id];
if(image_name != 'ouvar-pin-new-blue.png'){
fill_color_val = '#f24e82';
}
// alert(image_name);
}
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
});
circle = new google.maps.Circle({
map: map,
radius: 200000, // 10 miles in metres
fillColor: fill_color_val,
strokeColor: '#FFFFFF',
strokeWeight: 5,
fillOpacity: 1,
});
circle.bindTo('center', marker, 'position');
var labelText = locations[i][5];
var myOptions = {
content: labelText,
boxStyle: {
border: "none",
textAlign: "center",
fontSize: "12pt",
width: "50px",
color:'white',
},
disableAutoPan: true,
pixelOffset: new google.maps.Size(-25,-5),
position: latlng,
closeBoxURL: "",
isHidden: false,
pane: "floatPane",
enableEventPropagation: true,
zIndex: null,
};
// marker.setVisible(false);
var ibLabel = new InfoBox(myOptions);
ibLabel.open(map);
google.maps.event.addListener(ibLabel, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addListener(map, 'click', function () {
infowindow.close();
marker.open = false;
});
oms.addMarker(marker);
//oms.addMarker(marker);
}
window.map = map; // for debugging/exploratory use in console
window.oms = oms;
google.maps.event.addListener(infowindow, 'domready', function () {
var iwOuter = $('.gm-style-iw');
var iwBackground = iwOuter.prev();
iwBackground.children(':nth-child(2)').css({'display': 'none'});
iwBackground.children(':nth-child(4)').css({'display': 'none'});
iwBackground.children(':nth-child(1)').attr('style', function (i, s) {
return s + 'left: 76px !important;'
});
iwBackground.children(':nth-child(3)').find('div').children().css({'box-shadow': 'rgba(72, 181, 233, 0.6) 0px 1px 6px', 'z-index': '1'});
var iwCloseBtn = iwOuter.next();
iwCloseBtn.css({opacity: '1', right: '38px', top: '3px', border: '7px solid #fff', 'border-radius': '13px', 'padding': '6px', ' box-shadow': '0 14px 26px -12px rgba(239, 83, 80, 0.42), 0 4px 23px 0 rgba(0, 0, 0, 0.12), 0 8px 10px -5px rgba(239, 83, 80, 0.2)'});
if ($('.iw-content').height() < 140) {
$('.iw-bottom-gradient').css({display: 'none'});
}
iwCloseBtn.mouseout(function () {
$(this).css({opacity: '1'});
});
});
Can someone guide me how to enable click event for my custom circle as well.
If you want something to happen when someone clicks on the circle, you need to add a click listener to it. The code below will open the same infowindow on a click of the circle as the click listener on the marker (and reference it to the marker).
google.maps.event.addListener(circle, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
proof of concept fiddle
const citymap = {
chicago: {
name: "Chicago",
center: { lat: 41.878, lng: -87.629 },
population: 2714856,
},
newyork: {
name: "New York",
center: { lat: 40.714, lng: -74.005 },
population: 8405837,
},
losangeles: {
name: "Los Angeles",
center: { lat: 34.052, lng: -118.243 },
population: 3857799,
},
vancouver: {
name: "Vancouver",
center: { lat: 49.25, lng: -123.1 },
population: 603502,
},
};
function initMap() {
// Create the map.
const infowindow = new google.maps.InfoWindow({maxWidth: 350});
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 4,
center: {
lat: 37.09,
lng: -95.712
},
mapTypeId: "terrain",
});
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (const city in citymap) {
console.log("city:"+citymap[city].name);
// Add the circle for this city to the map.
const circle = new google.maps.Circle({
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100,
});
const marker = new google.maps.Marker({
position: citymap[city].center,
map: map,
});
google.maps.event.addListener(marker, 'click', (function(marker, city) {
return function() {
console.log("marker click:"+citymap[city].name);
infowindow.setContent(citymap[city].name);
infowindow.open(map, marker);
}
})(marker, city));
google.maps.event.addListener(circle, 'click', (function(marker, city) {
return function() {
console.log("circle click:"+citymap[city].name);
infowindow.setContent(citymap[city].name);
infowindow.open(map, marker);
}
})(marker, city));
}
}
window.initMap = initMap;
/*
* Always set the map height explicitly to define the size of the div element
* that contains the map.
*/
#map {
height: 100%;
}
/*
* Optional: Makes the sample page fill the window.
*/
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Circles</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
</head>
<body>
<div id="map"></div>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"
defer
></script>
</body>
</html>

Markers on multiple coordinates on Google Map in JavaScript

I have two sets of points coordinates that I need to connect on google map, like this, just much larger:
var start = ['42.81405, 12.4886861111', '32.7994444444, 20.506775', '44.8062644989, 20.5005495758'];
var end = ['47.81405, 18.4886861111', '33.7994444444, 21.506775', '39.8062644989, 16.5005495758'];
The first coordinate from "start" needs to be connected to the first coord from "end", and so on, until the end. Got that, but now I need to make "start" and "end" points more recognizable, put some kind of dots in a different color on them. What I have:
var geocoder;
var map;
function initialize() {
var center = new google.maps.LatLng(51.97559, 4.12565);
map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
var start = ['42.81405, 12.4886861111', '32.7994444444, 20.506775', '44.8062644989, 20.5005495758'];
var end = ['47.81405, 18.4886861111', '33.7994444444, 21.506775', '39.8062644989, 16.5005495758'];
var paths = [];
for (var i=0; i < end.length; i++){
var startCoords = start[i].split(",");
var startPt = new google.maps.LatLng(startCoords[0],startCoords[1]);
var endCoords = end[i].split(",");
var endPt = new google.maps.LatLng(endCoords[0],endCoords[1]);
paths.push([startPt, endPt]);
bounds.extend(startPt);
bounds.extend(endPt);
}
map.fitBounds(bounds);
var polyline = new google.maps.Polygon({
paths: paths,
strokeColor: 'red',
strokeWeight: 2,
strokeOpacity: 1
});
polyline.setMap(map);
}
google.maps.event.addDomListener(window, "load", initialize);
Any kind of help is welcomed.
The simplest thing you can just create markers for start and end points. Like the following code
for (var i=0; i < end.length; i++){
var startCoords = start[i].split(",");
var startPt = new google.maps.LatLng(startCoords[0],startCoords[1]);
var endCoords = end[i].split(",");
var endPt = new google.maps.LatLng(endCoords[0],endCoords[1]);
paths.push([startPt, endPt]);
bounds.extend(startPt);
bounds.extend(endPt);
//Create start and end markers
var markerStart = new google.maps.Marker({
position: startPt,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 3,
fillColor: 'blue',
strokeColor: 'blue'
},
draggable: true,
map: map
});
var markerEnd = new google.maps.Marker({
position: endPt,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 3,
fillColor: 'green',
strokeColor: 'green'
},
draggable: true,
map: map
});
}
It will give you something like
Code snippet
var map;
function initMap() {
var center = new google.maps.LatLng(51.97559, 4.12565);
map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
var start = ['42.81405, 12.4886861111', '32.7994444444, 20.506775', '44.8062644989, 20.5005495758'];
var end = ['47.81405, 18.4886861111', '33.7994444444, 21.506775', '39.8062644989, 16.5005495758'];
var paths = [];
for (var i=0; i < end.length; i++){
var startCoords = start[i].split(",");
var startPt = new google.maps.LatLng(startCoords[0],startCoords[1]);
var endCoords = end[i].split(",");
var endPt = new google.maps.LatLng(endCoords[0],endCoords[1]);
paths.push([startPt, endPt]);
bounds.extend(startPt);
bounds.extend(endPt);
//Create start and end markers
var markerStart = new google.maps.Marker({
position: startPt,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 3,
fillColor: 'blue',
strokeColor: 'blue'
},
draggable: true,
map: map
});
var markerEnd = new google.maps.Marker({
position: endPt,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 3,
fillColor: 'green',
strokeColor: 'green'
},
draggable: true,
map: map
});
}
map.fitBounds(bounds);
var polyline = new google.maps.Polygon({
paths: paths,
strokeColor: 'red',
strokeWeight: 2,
strokeOpacity: 1
});
polyline.setMap(map);
}
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap"
async defer></script>

Drawing polygons and each one must have a click event with google map API

I am dealing with an unusual problem. I am using google map API for drawing Polygons in the maps. My problem is that only the first one Polygon is working normally and firing event "click" works.
Here is my code, if you run the code snippet that you will see that only the first polygon is working normally the event click does not work on the others.
var map;
var infoWindow;
var listOfPolygons = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {lat: 24.886, lng: -70.268},
mapTypeId: 'terrain'
});
//Drawing tool
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['marker', 'circle', 'polygon', 'polyline', 'rectangle']
},
markerOptions: {icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'},
circleOptions: {
fillColor: '#ffff00',
fillOpacity: 1,
strokeWeight: 5,
clickable: false,
editable: true,
zIndex: 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
if (event.type == 'polygon') {
alert("Polygon Completed");
listOfPolygons.push(new google.maps.Polygon({
paths: event.overlay.getPath().getArray(),
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
}));
listOfPolygons[listOfPolygons.length - 1].setMap(map);
listOfPolygons[listOfPolygons.length - 1].addListener('click', showArrays);
alert(listOfPolygons.length);
}
});
infoWindow = new google.maps.InfoWindow();
}
/** #this {google.maps.Polygon} */
function showArrays(event) {
// Since this polygon has only one path, we can call getPath() to return the
// MVCArray of LatLngs.
var vertices = this.getPath();
var contentString = '<b>Bermuda Triangle polygon</b><br>' +
'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
'<br>';
// Iterate over the vertices.
for (var i =0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
xy.lng();
}
// Replace the info window's content and position.
infoWindow.setContent(contentString);
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCe-f8ouEtRm_ZeprT8-WEKulMy99VmJYU&libraries=drawing&callback=initMap"
async defer></script>
The polygon from the DrawingManager is on top of the Polygon with the click listener. You only want one version of the new Polygon, the one with the click listener added to it, hide the one from the DrawingManager (inside the overlaycomplete listener):
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
if (event.type == 'polygon') {
// hide polygon from DrawingManager
event.overlay.setMap(null);
// ....... existing code ............
proof of concept fiddle
code snippet:
var map;
var infoWindow;
var listOfPolygons = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: 24.886,
lng: -70.268
},
mapTypeId: 'terrain'
});
//Drawing tool
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['marker', 'circle', 'polygon', 'polyline', 'rectangle']
},
markerOptions: {
icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
},
circleOptions: {
fillColor: '#ffff00',
fillOpacity: 1,
strokeWeight: 5,
clickable: false,
editable: true,
zIndex: 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
if (event.type == 'polygon') {
console.log("Polygon Completed");
// hide polygon from DrawingManager
event.overlay.setMap(null);
listOfPolygons.push(new google.maps.Polygon({
paths: event.overlay.getPath().getArray(),
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
}));
listOfPolygons[listOfPolygons.length - 1].setMap(map);
listOfPolygons[listOfPolygons.length - 1].addListener('click', showArrays);
console.log(listOfPolygons.length);
}
});
infoWindow = new google.maps.InfoWindow();
}
/** #this {google.maps.Polygon} */
function showArrays(event) {
// Since this polygon has only one path, we can call getPath() to return the
// MVCArray of LatLngs.
var vertices = this.getPath();
var contentString = '<b>Bermuda Triangle polygon</b><br>' +
'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
'<br>';
// Iterate over the vertices.
for (var i = 0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
xy.lng();
}
// Replace the info window's content and position.
infoWindow.setContent(contentString);
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing&callback=initMap"
async defer></script>

Change marker icon options in google maps

I use this code to create my markers (TypeScript btw)
The options for the icon allows me to rotate and set a fill color of the marker.
But how can I change the fill color and rotation after creation?
I have found various responses here on SO, but they refer to changing the icon to a bitmap and swap between red and green bitmaps for example.
Which is not what I want.
var icon = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 4,
fillColor: "#ff5050", //<-- I want to change this after creation
fillOpacity: 1,
strokeWeight: 1,
rotation: 0 //<-- I want to change this after creation
};
var markerOptions = <google.maps.MarkerOptions>{
map: this.map,
icon: icon,
};
Anyone know?
Calling .setIcon on the marker works for me:
setInterval(function () {
angle += 30;
cnt++;
icon.rotation = angle;
icon.fillColor = colorArray[cnt % colorArray.length]
marker.setIcon(icon);
}, 1000);
working fiddle
working code snippet:
var map;
var angle = 0;
var marker;
var icon = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 4,
fillColor: "#ff5050", //<-- I want to change this after creation
fillOpacity: 1,
strokeWeight: 1,
anchor: new google.maps.Point(0, 5),
rotation: 0 //<-- I want to change this after creation
};
var colorArray = ["#ff0000", "#00FF00", "#0000FF", "#FFFF00", "#00FFFF", "#FF00FF"];
var cnt = 0;
function init() {
var startLatLng = new google.maps.LatLng(50.124462, -5.539994);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: startLatLng,
zoom: 12
});
var ptMarker = new google.maps.Marker({
position: new google.maps.LatLng(50.124462, -5.539994),
map: map,
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(4, 4)
}
});
marker = new google.maps.Marker({
position: new google.maps.LatLng(50.124462, -5.539994),
icon: icon
});
marker.setMap(map);
var circleMarker = new google.maps.Marker({
position: new google.maps.LatLng(50.124462, -5.539994),
map: map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 24,
strokeWeight: 2,
fillColor: '#009933',
fillOpacity: 0.001,
anchor: new google.maps.Point(0, 0)
}
});
setInterval(function () {
angle += 30;
cnt++;
icon.rotation = angle;
icon.fillColor = colorArray[cnt % colorArray.length]
marker.setIcon(icon);
}, 1000);
}
google.maps.event.addDomListener(window, 'load', init);
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" style="border: 2px solid #3872ac;"></div>

Circle fade out over time on Google Map [duplicate]

This question already has an answer here:
How do I fade out a circle in a Google Map, x seconds after I've added it to the map?
(1 answer)
Closed 8 years ago.
I am attempting to fade circles out with a setInterval on fillOpacity. However a console log shows the opacity changing but the appearance of the circle does not seem to change. Is there a different set function required to do this?
http://jsfiddle.net/faaxeskg/5/
setInterval(function() {
marker.fillOpacity -= .01;
console.log(marker.fillOpacity);
}, 200);
code snippet:
var map = null;
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Add 500 markers to the map at random locations
var southWest = new google.maps.LatLng(-31.203405, 125.244141);
var northEast = new google.maps.LatLng(-25.363882, 131.044922);
var bounds = new google.maps.LatLngBounds(southWest, northEast);
map.fitBounds(bounds);
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
setInterval(function() {
var position = new google.maps.LatLng(
southWest.lat() + latSpan * Math.random(),
southWest.lng() + lngSpan * Math.random());
var populationOptions = {
strokeOpacity: 0,
fillColor: '#FF0000',
fillOpacity: 0.65,
map: map,
center: position,
radius: 40000
};
var marker = new google.maps.Circle(populationOptions);
setInterval(function() {
marker.fillOpacity -= .01;
console.log(marker.fillOpacity);
}, 200);
setTimeout(function() {
marker.setMap(null);
delete marker;
}, 30000);
}, 2000);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry"></script>
<div id="map-canvas" style="float:left;width:100%;height:100%;"></div>
You need to associate the "opacity change" to the marker, you can do that with function closure (a createCircleMarker function).
Don't use undocumented properties. Use the documented methods.
marker.set("fillOpacity, marker.get("fillOpacity")-0.01);
working code snippet:
var map = null;
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Add 500 markers to the map at random locations
var southWest = new google.maps.LatLng(-31.203405, 125.244141);
var northEast = new google.maps.LatLng(-25.363882, 131.044922);
var bounds = new google.maps.LatLngBounds(southWest, northEast);
map.fitBounds(bounds);
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
setInterval(function() {
var position = new google.maps.LatLng(
southWest.lat() + latSpan * Math.random(),
southWest.lng() + lngSpan * Math.random());
var populationOptions = {
strokeOpacity: 0,
fillColor: '#FF0000',
fillOpacity: 0.65,
map: map,
center: position,
radius: 40000
};
createCircleMarker(populationOptions);
}, 2000);
}
function createCircleMarker(populationOptions) {
var marker = new google.maps.Circle(populationOptions);
setInterval(function() {
marker.set("fillOpacity",marker.get("fillOpacity")-0.05);
console.log(marker.fillOpacity);
}, 200);
setTimeout(function() {
marker.setMap(null);
delete marker;
}, 30000);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=geometry"></script>
<div id="map-canvas" style="float:left;width:100%;height:100%;"></div>

Categories

Resources