How to change the icon of transit stations in google maps? - google-maps

I have a google map with custom styling. I would like change the appearance of the rail and bus stations icons to my own png but they do not seem to function like other markers. Is it possible to change them?

One option would be to hide the transit icons (or just the bus icons), and put markers of your choice in the same locations. You do then need the locations of the stops.
proof of concept fiddle
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 53.3507456,
lng: -6.2393441
},
zoom: 16,
mapTypeControl: false,
styles: [{
featureType: 'transit',
elementType: 'labels.icon',
stylers: [{
visibility: 'off'
}]
}]
});
for (var i = 0; i < transitStops.length; i++) {
var tmark = new google.maps.Marker({
position: transitStops[i],
map: map,
icon: {
url: "https://www.geocodezip.net/mapIcons/bus_blue.png",
scaledSize: new google.maps.Size(10, 10),
anchor: new google.maps.Point(5, 5)
}
})
}
google.maps.event.addListener(map, 'click', function(evt) {
console.log("{placeId:" + evt.placeId + ", lat: " + evt.latLng.lat() + ", lng: " + evt.latLng.lng() + "}");
});
}
var transitStops = [{
placeId: "ChIJP_OC240OZ0gRTwu09OWnk_U",
lat: 53.347913,
lng: -6.247165
}, {
placeId: "ChIJFZJPbY0OZ0gRp8t6ffAVCWE",
lat: 53.347695,
lng: -6.243303
}, {
placeId: "ChIJOd0OQI0OZ0gRUKpFv3o7AEQ",
lat: 53.347759,
lng: -6.242445
}, {
placeId: "ChIJe1pTa40OZ0gR_e129---hi8",
lat: 53.347746,
lng: -6.24193
}, {
placeId: "ChIJKzM8uvIOZ0gRtYKquNyaiYc",
lat: 53.347528,
lng: -6.239698
}, {
placeId: "ChIJywS6evIOZ0gRhNm96pmOHlU",
lat: 53.347388,
lng: -6.236351
}, {
placeId: "ChIJF-4BzfMOZ0gRkEbmpj60Ub0",
lat: 53.349668,
lng: -6.235256
}, {
placeId: "ChIJQ6qDDfMOZ0gRBfF7TUP_Zi8",
lat: 53.350398,
lng: -6.238668
}, {
placeId: "ChIJQ9tx_PMOZ0gRJsmjoHdrYEI",
lat: 53.351781,
lng: -6.23502
}, {
placeId: "ChIJX9g7SvEOZ0gRys5vUWlD7aE",
lat: 53.352063,
lng: -6.233089
}, {
placeId: "ChIJH3fLzfYOZ0gR4UOqoWvdNhw",
lat: 53.352639,
lng: -6.232402
}, {
placeId: "ChIJn_6n1_YOZ0gRtovXaObKKWE",
lat: 53.352959,
lng: -6.231608
}, {
placeId: "ChIJXWdle4wOZ0gRGAyVKltGjlA",
lat: 53.351128,
lng: -6.245534
}, {
placeId: "ChIJ81mp4IsOZ0gROlwgkhh__eA",
lat: 53.35287,
lng: -6.248538
}, {
placeId: "ChIJtanR-PAOZ0gRydiUCW5F6VE",
lat: 53.349911,
lng: -6.230235
}, {
placeId: "ChIJ86GfP_QOZ0gRxuS4lSrV_EU",
lat: 53.35366366064975,
lng: -6.236715316772461
}, {
placeId: "ChIJ2XaPUvQOZ0gRdutDSaj0Ko4",
lat: 53.354649828682476,
lng: -6.23798131942749
}, {
placeId: "ChIJT6lqq_UOZ0gRr00DPcLv8WU",
lat: 53.35484193668282,
lng: -6.238517761230469
}, {
placeId: "ChIJPWurjI8OZ0gRgRn4fsIACMc",
lat: 53.347169750741884,
lng: -6.25422477722168
}, {
placeId: "ChIJpWwGCJEOZ0gRPZ-JB7vXAAU",
lat: 53.343377977116916,
lng: -6.248044967651367
}, {
placeId: "ChIJW6E5POsOZ0gRhU0Mt66cLcg",
lat: 53.33979085385975,
lng: -6.2381744384765625
}, {
placeId: "ChIJG4-0NcIOZ0gRbapaqYSiEm0",
lat: 53.33384581380873,
lng: -6.22899055480957
}];
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

Related

need to get an external button to link to maps when clicked on

I need help linking buttons to cities. When clicked, opens a new map which then zooms in and I can have places of interest also. This is my file below and I am not the best at coding so help appreciated please.
I haven't included the HTML file as its so basic and was more what I needed to add here.
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
zoom: 3,
center: {
lat: 50.7436337,
lng: 18.4208039
}
});
to loop around
Need help to link buttons to cities that when clicked upon opens up to a map of that city
var labels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
My places are outlined below of the cities I want in my buttons:
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
map: map,
icon: icons[feature.type].icon,
});
}
The map of the world:
var map;
var InforObj = [];
var centerCords = {
lat: 50.7436337,
lng: 18.4208039
};
var markersOnMap = [{
placeName: "Amsterdam (Johan Cryuff Arena)",
LatLng: [{
lat: 52.314371,
lng: 4.941964
}],
},
{ placeName: "Baku (Olympic Stadium)",
LatLng: [{
lat: 40.4300,
lng: 49.9196
}]
},
{ placeName: "Bilbao (San Mames)",
LatLng: [{
lat: 43.2641,
lng: -2.9494
}]
},
{ placeName: "Bucharest (Arena Nationala)",
LatLng: [{
lat: 44.437139,
lng: 26.152579
}]
},
{ placeName: "Budapest (Puskas Arena)",
LatLng: [{
lat: 47.503172,
lng: 19.097022
}]
},
{ placeName: "Copenhagen (Parken Stadium)",
LatLng: [{
lat: 55.702701,
lng: 12.572433
}]
},
{ placeName: "Dublin (Aviva Stadium)",
LatLng: [{
lat: 53.335232,
lng: -6.228457
}]
},
{ placeName: "Glasgow (Hampden Park)",
LatLng: [{
lat: 55.825842,
lng: -4.252048
}]
},
{ placeName: "London (Wembley Stadium)",
LatLng: [{
lat: 51.556021,
lng: -0.279519
}]
},
{ placeName: "Munich (Allianz Arena)",
LatLng: [{
lat: 48.2188,
lng: 11.624707
}]
},
{ placeName: "Rome (Stadio Olimpico)",
LatLng: [{
lat: 41.934077,
lng: 12.454725
}]
},
{ placeName: "Saint Petersburg (Krestovsky Stadium)",
LatLng: [{
lat: 59.972728,
lng: 30.221405
}]
},
];
List of the cities above:
window.onload = function () {
initMap();
};
function addMarkerInfo() {
for (var i = 0; i < markersOnMap.length; i++) {
var contentString = '<div id="content"><h1>' + markersOnMap[i].placeName +
'</h1><p>Lorem ipsum dolor sit amet, vix mutat posse suscipit id, vel ea tantas omittam detraxit.</p></div>';
const marker = new google.maps.Marker({
position: markersOnMap[i].LatLng[0],
map: map,
});
const infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 200
});
marker.addListener('click', function () {
closeOtherInfo();
infowindow.open(marker.get('map'), marker);
InforObj[0] = infowindow;
});
}
}
All part of the same code and I am not sure how its done properly
function closeOtherInfo() {
if (InforObj.length > 0) {
// detach the info-window from the marker ... undocumented in the API docs
InforObj[0].set("marker", null);
// and close it
InforObj[0].close();
// blank the array
InforObj.length = 0;
}
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: centerCords
});
addMarkerInfo();
}
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(48.1293954, 12.556663), //Setting Initial Position
zoom: 10
});
}
my file path
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
This is my javascript code

add multiple gmap marker

i have a vue2-google-map apps that display map.
before this i using this code
<GmapMarker
ref="myMarker"
:position="google && new google.maps.LatLng(1.38, 103.8)"
/>
<GmapMarker
ref="myMarker"
:position="google && new google.maps.LatLng(3.1488976, 101.6126774)"
/>
to display multiple marker, but if the latlng data is too many, it will be many need to be create.
my idea is to take data from
const latlng = [
{
lat: value,
lng: value,
},
{
lat: value,
lng: value,
},
and apply {{latlng}} into <GmapMarker :position="google && new google.maps.LatLn({{latlng.lng}},{{latlng.lat}})">
but i have problem to apply that {{latlng}} into the marker.
can someone explain how to apply them?
For generating multiple markers your need to push latitude and longitude in the marker collection and then iterate the marker.i have updated code as per the requirement.
<template>
<div>
<GmapMap
ref="gmap"
:center="getCenter()"
:zoom="11"
style="height: 500px;margin: 0px -8px;"
class="no-padding"
:options="getOptions()"
>
<GmapMarker
:key="index"
v-for="(m, index) in getMarkers()"
:position="m.position"
:clickable="true"
:draggable="false"
:title="m.title"
:icon="m.icon"
#click="clicked()"
/>
</GmapMap>
</div>
</template>
<script>
import MarkerClusterer from "marker-clusterer-plus";
export default {
name: "SiteMap",
props: [],
methods: {
getOptions() {
return {
zoomControl: true,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false,
disableDefaultUi: false
};
},
clicked() {
// after click
},
getCenter() {
return {
lat: 37.12523,
lng: -122.1252
};
},
getMarkers() {
// generating markers for site map
var markers = [];
// remove this after lat long received from api.
const tempLatLong = [
{ lat: 37.9068361, lng: -122.116971 },
{ lat: 37.9168362, lng: -122.076972 },
{ lat: 37.9268363, lng: -122.136973 },
{ lat: 37.9368364, lng: -122.146974 },
{ lat: 37.9468365, lng: -122.106975 },
{ lat: 37.9568366, lng: -122.166976 },
{ lat: 37.9668367, lng: -122.176977 },
{ lat: 37.9768368, lng: -122.016978 },
{ lat: 37.9868369, lng: -122.196979 }
];
for(let i=0;i<tempLatLong.length;i++){
markers.push({
position: tempLatLong[i],
title: 'test title',
icon: this.getSiteIcon(1) // if you want to show different as per the condition.
});
}
return markers;
},
getSiteIcon(status) {
try {
switch (status) {
case 1:
return require("#/assets/images/icons/map-marker-online.svg");
break;
case 2:
return require("#/assets/images/icons/map-marker-critical.svg");
break;
case 3:
return require("#/assets/images/icons/map-marker-offline.svg");
break;
case 4:
return require("#/assets/images/icons/map-marker-lifesafety.svg");
break;
default:
return require("#/assets/images/icons/map-marker-online.svg");
}
} catch (e) {
return null;
}
},
},
components: {},
created() {},
mounted() {
}
};
</script>
<style scoped></style>

google maps roads api looping - how to stop

I've implemented the code seen at:
https://developers.google.com/maps/documentation/roads/inspector.
In each of the examples on this page, the marker animation loops.
How are you supposed to stop the looping so that the icon remains at the end point until more coordinates are fed to it, at which point I'll animate from the last gps coord to the newest gps coord which I just received?
I just don't want to see the course traveled over and over again.
To stop the animation, cancel the setInterval when the icon reaches the end of the polyline.
function animateCircle(polyline) {
var count = 0;
// fallback icon if the poly has no icon to animate
var defaultIcon = [
{
icon: lineSymbol,
offset: '100%'
}
];
handle = window.setInterval(function() {
if ((count+1) == 200)
window.clearInterval(handle);
count = (count + 1) % 200;
var icons = polyline.get('icons') || defaultIcon;
icons[0].offset = (count / 2) + '%';
polyline.set('icons', icons);
}, 20);
}
proof of concept fiddle
code snippet:
/**
* Animate an icon along a polyline
* #param {Object} polyline The line to animate the icon along
*/
function animateCircle(polyline) {
var count = 0;
// fallback icon if the poly has no icon to animate
var defaultIcon = [{
icon: lineSymbol,
offset: '100%'
}];
handle = window.setInterval(function() {
// when reaches end of polyline
if ((count + 1) == 200) {
// cancel the interval timer
window.clearInterval(handle);
// hide the circle
var icons = polyline.get('icons') || defaultIcon;
icons[0].icon.strokeOpacity = 0;
polyline.set('icons', icons);
}
count = (count + 1) % 200;
var icons = polyline.get('icons') || defaultIcon;
icons[0].offset = (count / 2) + '%';
polyline.set('icons', icons);
}, 20);
}
// Icons for markers
var RED_MARKER = 'https://maps.google.com/mapfiles/ms/icons/red-dot.png';
var GREEN_MARKER = 'https://maps.google.com/mapfiles/ms/icons/green-dot.png';
var BLUE_MARKER = 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png';
var YELLOW_MARKER = 'https://maps.google.com/mapfiles/ms/icons/yellow-dot.png';
// URL for places requests
var PLACES_URL = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=';
// URL for Speed limits
var SPEED_LIMIT_URL = 'https://roads.googleapis.com/v1/speedLimits';
var coords;
/**
* Current Roads API threshold (subject to change without notice)
* #const {number}
*/
var DISTANCE_THRESHOLD_HIGH = 300;
var DISTANCE_THRESHOLD_LOW = 200;
/**
* #type Array<ExtendedLatLng>
*/
var originals = []; // the original input points, a list of ExtendedLatLng
var interpolate = true;
var map;
var placesService;
var originalCoordsLength;
// Settingup Arrays
var infoWindows = [];
var markers = [];
var placeIds = [];
var polylines = [];
var snappedCoordinates = [];
var distPolylines = [];
// Symbol that gets animated along the polyline
var lineSymbol = {
path: google.maps.SymbolPath.CIRCLE,
scale: 8,
strokeColor: '#005db5',
strokeWidth: '#005db5'
};
// Initialize
function initialize() {
// Centre the map on Sydney
var mapOptions = {
center: {
'lat': -33.870315,
'lng': 151.196532
},
zoom: 16
};
// Map object
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// Places object
placesService = new google.maps.places.PlacesService(map);
drawSnappedPolyline();
// Draw the polyline for the snapToRoads API response
// Call functions to add markers and infowindows for each snapped
// point along the polyline.
function drawSnappedPolyline(snappedCoords) {
var snappedCoords = [{
lat: -33.87031296432842,
lng: 151.19649532278828,
originalIndex: 0,
interpolated: false
},
{
lat: -33.8702971,
lng: 151.1964966,
interpolated: true
},
{
lat: -33.8702971,
lng: 151.1964966,
interpolated: true
},
{
lat: -33.8700888,
lng: 151.19690029999998,
interpolated: true
},
{
lat: -33.8700888,
lng: 151.19690029999998,
interpolated: true
},
{
lat: -33.869997,
lng: 151.197091,
interpolated: true
},
{
lat: -33.8699822,
lng: 151.1971317,
interpolated: true
},
{
lat: -33.8699669,
lng: 151.1971912,
interpolated: true
},
{
lat: -33.8699669,
lng: 151.1971912,
interpolated: true
},
{
lat: -33.869954,
lng: 151.1972377,
interpolated: true
},
{
lat: -33.8699449,
lng: 151.1972855,
interpolated: true
},
{
lat: -33.86994270100937,
lng: 151.197353292079,
originalIndex: 1,
interpolated: false
},
{
lat: -33.8699414,
lng: 151.19739339999998,
interpolated: true
},
{
lat: -33.8699441,
lng: 151.1974702,
interpolated: true
},
{
lat: -33.8699507,
lng: 151.19755139999998,
interpolated: true
},
{
lat: -33.8699602,
lng: 151.1976302,
interpolated: true
},
{
lat: -33.86997848255702,
lng: 151.19772949764274,
originalIndex: 2,
interpolated: false
},
{
lat: -33.869981300000006,
lng: 151.19774479999998,
interpolated: true
},
{
lat: -33.8700129,
lng: 151.1978469,
interpolated: true
},
{
lat: -33.8700129,
lng: 151.1978469,
interpolated: true
},
{
lat: -33.8700458,
lng: 151.1979242,
interpolated: true
},
{
lat: -33.8700834,
lng: 151.1979993,
interpolated: true
},
{
lat: -33.8701059,
lng: 151.1980374,
interpolated: true
},
{
lat: -33.870184300000005,
lng: 151.1981381,
interpolated: true
},
{
lat: -33.8702143,
lng: 151.1981743,
interpolated: true
},
{
lat: -33.8702143,
lng: 151.1981743,
interpolated: true
},
{
lat: -33.8702902,
lng: 151.19825269999998,
interpolated: true
},
{
lat: -33.87031617902999,
lng: 151.19827540632983,
originalIndex: 3,
interpolated: false
},
{
lat: -33.8703672,
lng: 151.19832,
interpolated: true
},
{
lat: -33.870480199999996,
lng: 151.19839969999998,
interpolated: true
},
{
lat: -33.870480199999996,
lng: 151.19839969999998,
interpolated: true
},
{
lat: -33.8705388,
lng: 151.1984269,
interpolated: true
},
{
lat: -33.87057888561142,
lng: 151.19844125817298,
originalIndex: 4,
interpolated: false
},
{
lat: -33.870625219935086,
lng: 151.19845785457534,
originalIndex: 5,
interpolated: false
},
{
lat: -33.8706823,
lng: 151.1984783,
interpolated: true
},
{
lat: -33.8706823,
lng: 151.1984783,
interpolated: true
},
{
lat: -33.870718800000006,
lng: 151.1984865,
interpolated: true
},
{
lat: -33.8708181,
lng: 151.19850399999999,
interpolated: true
},
{
lat: -33.8708644,
lng: 151.1985081,
interpolated: true
},
{
lat: -33.870908899999996,
lng: 151.1985078,
interpolated: true
},
{
lat: -33.87095031058638,
lng: 151.19850565885983,
originalIndex: 7,
interpolated: false
},
{
lat: -33.8709998,
lng: 151.19850309999998,
interpolated: true
},
{
lat: -33.87103822739919,
lng: 151.1984996185936,
originalIndex: 8,
interpolated: false
},
{
lat: -33.8713497,
lng: 151.1984714,
interpolated: true
},
{
lat: -33.8713497,
lng: 151.1984714,
interpolated: true
},
{
lat: -33.8718054,
lng: 151.1984326,
interpolated: true
},
{
lat: -33.8719381,
lng: 151.1984352,
interpolated: true
},
{
lat: -33.87203169684805,
lng: 151.198429447748,
originalIndex: 9,
interpolated: false
}
];
var snappedPolyline = new google.maps.Polyline({
path: snappedCoords,
strokeColor: '#005db5',
strokeWeight: 6,
icons: [{
icon: lineSymbol,
offset: '100%'
}]
});
snappedPolyline.setMap(map);
animateCircle(snappedPolyline);
polylines.push(snappedPolyline);
var placeIds = [
"ChIJS6cYMjeuEmsRVxRklOwdF8o",
"ChIJS6cYMjeuEmsRVxRklOwdF8o",
"ChIJ-dDXMDeuEmsRSUxWOfxOpYA",
"ChIJ-dDXMDeuEmsRSUxWOfxOpYA",
"ChIJKVpuODeuEmsRjffu1J1v888",
"ChIJKVpuODeuEmsRjffu1J1v888",
"ChIJKVpuODeuEmsRjffu1J1v888",
"ChIJKVpuODeuEmsRjffu1J1v888",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJrV1uWzeuEmsR2N5RA6d2SEE",
"ChIJrV1uWzeuEmsR2N5RA6d2SEE",
"ChIJrV1uWzeuEmsR2N5RA6d2SEE",
"ChIJrV1uWzeuEmsR2N5RA6d2SEE",
"ChIJrV1uWzeuEmsR2N5RA6d2SEE",
"ChIJrV1uWzeuEmsR2N5RA6d2SEE",
"ChIJeUaSWTeuEmsRGB2FlgUyPzE",
"ChIJeUaSWTeuEmsRGB2FlgUyPzE",
"ChIJeUaSWTeuEmsRGB2FlgUyPzE",
"ChIJeUaSWTeuEmsRGB2FlgUyPzE",
"ChIJeUaSWTeuEmsRGB2FlgUyPzE",
"ChIJOU6hVzeuEmsRlJsTGD1vpqU",
"ChIJOU6hVzeuEmsRlJsTGD1vpqU",
"ChIJOU6hVzeuEmsRlJsTGD1vpqU",
"ChIJOU6hVzeuEmsRlJsTGD1vpqU",
"ChIJOU6hVzeuEmsRlJsTGD1vpqU",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJ9SmzqTCuEmsRbkJlaklnr2s",
"ChIJ9SmzqTCuEmsRbkJlaklnr2s",
"ChIJ9SmzqTCuEmsRbkJlaklnr2s",
"ChIJ9SmzqTCuEmsRbkJlaklnr2s"
];
for (var i = 0; i < snappedCoords.length; i++) {
var marker = addMarker(snappedCoords[i]);
}
}
} // End init function
// Call the initialize function once everything has loaded
google.maps.event.addDomListener(window, 'load', initialize);
/**
* Add a marker to the map and check for special 'interpolated'
* and 'unsnapped' properties to control which colour marker is used
* #param {ExtendedLatLng} coords - Coords of where to add the marker
* #return {!Object} marker - the marker object created
*/
function addMarker(coords) {
var marker = new google.maps.Marker({
position: coords,
title: coords.lat + ',' + coords.lng,
map: map,
opacity: 0.5,
icon: RED_MARKER
});
// Coord should NEVER be interpolated AND unsnapped
if (coords.interpolated) {
marker.setIcon(BLUE_MARKER);
} else if (!coords.related) {
marker.setIcon(YELLOW_MARKER);
} else if (coords.originalIndex != undefined) {
marker.setIcon(RED_MARKER);
addCorrespondence(coords, marker);
} else {
marker.setIcon({
url: GREEN_MARKER,
scaledSize: {
width: 20,
height: 20
}
});
addCorrespondence(coords, marker);
}
// Make markers change opacity when the mouse scrubs across them
marker.addListener('mouseover', function(mevt) {
marker.setOpacity(1.0);
});
marker.addListener('mouseout', function(mevt) {
marker.setOpacity(0.5);
});
coords.marker = marker; // Save a reference for easy access later
markers.push(marker);
return marker;
}
/**
* Fit the map bounds to the current set of markers
* #param {Array<Object>} markers Array of all map markers
*/
function fitBounds(markers) {
var bounds = new google.maps.LatLngBounds;
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
font-family: Roboto, Noto, sans-serif;
}
#map {
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places,geometry">
</script>
<div id="map">
</div>

can't define style on google maps Polygon

I'm trying to add some polygons on data layer. I have defined the colors that they should have. My problem is that I can't set a color for each but if I set the style it becomes like a global style.
My JS FIDDLE
I tried like , with an random color:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: -34.872, lng: 155.252},
});
var innerCoords1 = [
{lat: -33.364, lng: 154.207},
{lat: -34.364, lng: 154.207},
{lat: -34.364, lng: 155.207},
{lat: -33.364, lng: 155.207}
];
var innerCoords2 = [
{lat: -33.364, lng: 156.207},
{lat: -34.364, lng: 156.207},
{lat: -34.364, lng: 157.207},
{lat: -33.364, lng: 157.207}
];
var innerCoords3 = [
{lat: -33.979, lng: 157.987},
{lat: -34.979, lng: 157.987},
{lat: -34.979, lng: 158.987},
{lat: -33.979, lng: 158.987}
];
map.data.add({geometry: new google.maps.Data.Polygon([innerCoords1,
innerCoords2,
innerCoords3])});
map.data.setStyle(function(feature) {return {fillColor: getRandomColor(),strokeWeight: 5}})
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
how can I define style(fill color) for each rectangle to be different and unique, can someone help me please?
Your getRandomColor function isn't giving you different colors because it is only called once. If I assign each Polygon an id and index into an array based on that, I get different colors (I assume you don't really need random colors).
var colorArray = ["#FF0000", "#00FF00", "#0000FF"];
map.data.setStyle(function(feature) {
var color = colorArray[feature.getId()];
return {
fillColor: color,
strokeWeight: 5
}
});
It does work for me if I call it the same as above (outside of the returned style):
map.data.setStyle(function(feature) {
var color = getRandomColor();
return {
fillColor: color,
strokeWeight: 5
}
});
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {
lat: -34.872,
lng: 155.252
},
});
var innerCoords1 = [{
lat: -33.364,
lng: 154.207
}, {
lat: -34.364,
lng: 154.207
}, {
lat: -34.364,
lng: 155.207
}, {
lat: -33.364,
lng: 155.207
}];
var innerCoords2 = [{
lat: -33.364,
lng: 156.207
}, {
lat: -34.364,
lng: 156.207
}, {
lat: -34.364,
lng: 157.207
}, {
lat: -33.364,
lng: 157.207
}];
var innerCoords3 = [{
lat: -33.979,
lng: 157.987
}, {
lat: -34.979,
lng: 157.987
}, {
lat: -34.979,
lng: 158.987
}, {
lat: -33.979,
lng: 158.987
}];
map.data.add({
id: 0,
geometry: new google.maps.Data.Polygon([innerCoords1])
});
map.data.add({
id: 1,
geometry: new google.maps.Data.Polygon([innerCoords2])
});
map.data.add({
id: 2,
geometry: new google.maps.Data.Polygon([innerCoords3])
});
var colorArray = ["#FF0000", "#00FF00", "#0000FF"];
map.data.setStyle(function(feature) {
var color = colorArray[feature.getId()];
return {
fillColor: color,
strokeWeight: 5
}
});
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
console.log(color);
return color;
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Drawing lines on google maps api

I am able to draw the lines on the maps using the following code:
var flightPlanCoordinates1 = [
{ lat: 22.53412218657744, lng: -95.4580076783896 },
{ lat: 25.265810430433756, lng: -96.51269517838955 },
{ lat: 24.308304859959954, lng: -92.4916990846396 },
{ lat: 28.150714091845007, lng: -94.07373033463955 },
{ lat: 26.530793950651773, lng: -89.92089830338955 },
{ lat: 25.5635039073037, lng: -87.63574205338955 },
{ lat: 26.491469591982202, lng: -85.30664049088955 },
{ lat: 28.65323578152034, lng: -86.80078111588955 },
{ lat: 28.845876611067364, lng: -88.91015611588955 },
{ lat: 27.587415049297192, lng: -88.33886705338955 },
{ lat: 25.84068541364038, lng: -94.00781236588955 }
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates1,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
But in a real application as we are getting data from db and populating it , I am not able to get the lines on the map
So, here is the object declaration and initialization:
flightPlanCoordinates = [];
for (var i = 0; i < jsonOut.length; i++) {
jsonCor["lat"] = jsonOut[i]["lat"];
jsonCor["long"] = jsonOut[i]["long"];
flightPlanCoordinates.push(jsonCor);
}
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
The data in the object is as below:
0: Object
lat: 23.222417047162825
long: -95.45800767838955
__proto__: Object
1:Object
so on which is exactly in the example shown above.
What is the problem with the object which is constructed?
You probably need to do this:
for (var i = 0; i < jsonOut.length; i++) {
flightPlanCoordinates.push({
lat: parseFloat(jsonOut[i]["lat"]),
lng: parseFloat(jsonOut[i]["long"]
});
}
Firstly make the structure of your coordinates match what you were doing originally, i.e. {lat: x, lng: y} instead of {lat, x, long: y}.
Secondly because you're reading it from JSON, you probably also need to do parseFloat() on the values, otherwise they're likely to be strings.