I'm using ACF to create maps from custom product fields in WordPress/Woocommerce.
/**
* initMarker
*
* Creates a marker for the given jQuery element and map.
*
* #date 22/10/19
* #since 5.8.6
*
* #param jQuery $el The jQuery element.
* #param object The map instance.
* #return object The marker instance.
*/
function initMarker( $marker, map ) {
// Get position from marker.
var lat = $marker.data('lat');
var lng = $marker.data('lng');
var latLng = {
lat: parseFloat( lat ),
lng: parseFloat( lng )
};
// Create marker instance.
var marker = new google.maps.Marker({
position: latLng,
map: map
});
// Append to reference for later use.
map.markers.push( marker );
// If marker contains HTML, add it to an infoWindow.
if( $marker.html() ){
// Create info window.
var infowindow = new google.maps.InfoWindow({
content: $marker.html()
});
// Show info window when marker is clicked.
google.maps.event.addListener(marker, 'click', function() {
infowindow.open( map, marker );
});
}
}
I'd like to style my initial marker with custom colors.
Google Maps documentation instructs how to work with a defined position, as follows, but if I delete the position line, my map just disappears.
// [START maps_advanced_markers_basic_style_background]
// Change the background color.
const pinViewBackground = new google.maps.marker.PinView({
background: "#FBBC04",
});
const markerViewBackground = new google.maps.marker.AdvancedMarkerView({
map,
position: { lat: 37.419, lng: -122.01 },
content: pinViewBackground.element,
});
// [END maps_advanced_markers_basic_style_background]
// [START maps_advanced_markers_basic_style_border]
// Change the border color.
const pinViewBorder = new google.maps.marker.PinView({
borderColor: "#137333",
});
const markerViewBorder = new google.maps.marker.AdvancedMarkerView({
map,
position: { lat: 37.415, lng: -122.03 },
content: pinViewBorder.element,
});
// [END maps_advanced_markers_basic_style_border]
Is there a way I can apply the above mentioned styles in a dynamic map?
Yes, you can style your markers dynamically using the icon property of the google.maps.Marker object.
You can specify a URL to a custom icon, or you can create a custom icon programmatically using a google.maps.Symbol object, which allows you to set various properties such as the fill color, stroke color, and path.
Here's an example that sets the marker's fill color to blue:
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: {
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
fillColor: '#0000FF',
fillOpacity: 1,
strokeColor: '#000000',
strokeWeight: 2,
scale: 1
}
});
You can adjust the path and other properties to get the desired appearance for your markers.
Related
I have a google map with a set of map markers. I chose to draw the map markers with a function called pinSymbol() - instead of using the default image.
I want to change the color of the pin when it is clicked, but I can't get it to update. With the current code I can change the property of the icon, I can see this with console.log(marker), however it won't update the color on the map.
Question: How do I redraw the icon on click?
This is my code.
// Go through all restaurants and get facebook info,
// then create a marker for each one.
restaurants.forEach(function(restaurant){
getFacebookInfo(restaurant);
}); // end forEach loop
// Get data from Facebook Graph API and create a marker
function getFacebookInfo(restaurant){
$.ajax({
url : '/restaurants/' + restaurant.id,
type : 'GET',
dataType:'json',
success : function(data) {
restaurant.about = data.about;
createMarker(restaurant);
},
error : function(request, error) {
console.log(error);
alert("We're having some trouble getting a restaurant's info from Facebook. " +
"Please check your internet connection and try refreshing the page.")
}
});
}
// Create a marker on the map for a location
function createMarker(restaurant){
var position = restaurant.location;
var infowindow = new google.maps.InfoWindow({
maxWidth: 200
});
restaurant.marker = new google.maps.Marker({
position: position,
map: map,
icon: pinSymbol('#CD212A', '#CD212A'),
name: restaurant.name,
id: restaurant.id,
about: restaurant.about,
animation: google.maps.Animation.DROP
});
// Push the marker to array of markers
markers.push(restaurant.marker);
// Call populateInfoWindow function
populateInfoWindow(restaurant.marker, infowindow);
// Add infowindow as a property to restaurant
// this makes it available for use outside this function.
restaurant.infowindow = infowindow;
This is where I'm stuck:
// Open infowindow when marker is clicked and change color
restaurant.marker.addListener('click', function(){
this.icon = pinSymbol('#EED4D9', '#EED4D9');
console.log(restaurant.marker);
infowindow.open(map, this);
});
}
pinSymbol Function
// Create pin for google map marker
function pinSymbol(color, strokeColor) {
return {
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
fillColor: color,
fillOpacity: 1,
strokeColor: strokeColor,
strokeWeight: 1,
scale: 1,
labelOrigin: new google.maps.Point(0,-29)
};
}
There is no (documented) .icon property of a marker. Don't use it. Use the documented .setIcon method:
// Open infowindow when marker is clicked and change color
restaurant.marker.addListener('click', function() {
this.setIcon(pinSymbol('#EED4D9', '#EED4D9'));
console.log(restaurant.marker);
infowindow.open(map, this);
});
proof of concept fiddle
code snippet:
var geocoder;
var map;
var markers = [];
function initialize() {
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
});
createMarker({
name: "center",
id: 2,
about: "",
location: {
lat: 37.4419,
lng: -122.1419
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
// Create a marker on the map for a location
function createMarker(restaurant) {
var position = restaurant.location;
var infowindow = new google.maps.InfoWindow({
maxWidth: 200
});
restaurant.marker = new google.maps.Marker({
position: position,
map: map,
icon: pinSymbol('#CD212A', '#CD212A'),
name: restaurant.name,
id: restaurant.id,
about: restaurant.about,
animation: google.maps.Animation.DROP
});
// Push the marker to array of markers
markers.push(restaurant.marker);
// Call populateInfoWindow function
populateInfoWindow(restaurant.marker, infowindow);
// Add infowindow as a property to restaurant
// this makes it available for use outside this function.
restaurant.infowindow = infowindow;
// Open infowindow when marker is clicked and change color
restaurant.marker.addListener('click', function() {
if (this.getIcon().fillColor != "#EED4D9") {
this.setIcon(pinSymbol('#EED4D9', '#EED4D9'));
} else {
this.setIcon(pinSymbol('#CD212A', '#CD212A'));
}
console.log(restaurant.marker);
infowindow.open(map, this);
});
}
// Create pin for google map marker
function pinSymbol(color, strokeColor) {
return {
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
fillColor: color,
fillOpacity: 1,
strokeColor: strokeColor,
strokeWeight: 1,
scale: 1,
labelOrigin: new google.maps.Point(0, -29)
};
}
function populateInfoWindow(marker, infowindow) {
infowindow.setContent("content");
};
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>
I'm looking how to add specific markers to my gmap.
This is the code:
LatLng coord1 = new LatLng (y, x);
advancedModel.addOverlay(new Marker(coord1, "test", "orange.png", "http://maps.google.com/mapfiles/ms/micons/blue-dot.png"));
I want to add my specific marker which is in /resources/images not this one http://maps.google.com/mapfiles/ms/micons/blue-dot.png
Can you help?
You can add custom markers in Google Maps and you can also change the marker icon, depending on the type of feature the marker's being added to. Each point of interest in the list of campus features has a type attribute.
Below code is a sample code snippet how to add custom markers:
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var icons = {
parking: {
icon: iconBase + 'parking_lot_maps.png'
},
library: {
icon: iconBase + 'library_maps.png'
},
info: {
icon: iconBase + 'info-i_maps.png'
}
};
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map
});
}
You can do something like this:
Marker newMarker = new Marker(new LatLng(latitude, longitude));
newMarker.setIcon("resources/media/marker-blue-dot.png");
simpleModel.addOverlay(newMarker);
I have successfully added a custom image for the marker on the google map. The problem is such that the default marker that is balloon still appears along with the new image.
How should remove the default marker and only use the custom image?
The following is the code block that I have used :
var image = "image url";
marker = createMarker(point, address1, town, postcode, SiteName);
marker = new google.maps.Marker({
position: point,
map: map,
icon: image
});
The code for createMarker function is as follows:
function createMarker(point, address1, town, postcode, sitename) {
var html;
var infowindow;
html = '<b>' + sitename + '</b>' + '<br/>' + address1 + '<br/>' + town + '<br/>' + postcode;
var marker = new google.maps.Marker({ position: point, map: map });
google.maps.event.addListener(marker, "mouseover", function () {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({ content: html });
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, "click", function () {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({ content: html });
infowindow.open(map, marker);
});
return marker;
}
Icon property- can be set an image OR vector path:
Example-
marker = new google.maps.Marker({
position: new google.maps.LatLng(-25.363882, 131.044922),
icon: {
path: google.maps.SymbolPath.CIRCLE,
},
or
icon: url of an image,
draggable: true,
map: map,
animation: google.maps.Animation.DROP
});
This icon property will override the default ballon icon
Or if you want to set the icon later in the code- just write- marker.setIcon("your url");
UPDATE: You are actually creating two markers at the same location, one with the custom icon and with default icon.
Here-
marker = createMarker(point, address1, town, postcode, SiteName);`// marker1`
marker = new google.maps.Marker({ `...... //marker 2`
So combine these both-
function createMarker(point, address1, town, postcode, sitename, image) {
//code
var marker = new google.maps.Marker({ position: point, map: map, icon:image });
Can somebody help me put the current location in front of all others? I have read about MAX_ZINDEX and setZindex() but I cannot understand it. This is my code:
var latlng = new google.maps.LatLng(lat,lng);
var image = "";
var currentplace = "Ohla Hotel";
var zInd = "";
if( name == currentplace ) {
image = "../img/hotel_icon.png";
}
else {
image = "../img/home_icon.png";
}
//alert();
var maxZindex = google.maps.Marker.MAX_ZINDEX;
if( name == currentplace ) {
zInd = (maxZindex + 1);
}
var locationDescription = this.locationDescription;
var marker = new google.maps.Marker({
map: map,
position: latlng,
title:'pk:'+name,
MAX_ZINDEX: zInd,
icon: image
});
bounds.extend(latlng);
setMarker(map, marker, name, locationDescription);
MAX_ZINDEXis a constant, not an attribute of a marker.
The relevant MarkerOption is zIndex:
var marker = new google.maps.Marker({
map: map,
position: latlng,
title:'pk:'+name,
zIndex: zInd,
icon: image
});
This sets the marker's zIndex attribute to the value you have calculated, which is one more than the API's maximum value.
Most of your code makes sense, but your definition of the MarkerOptionsapi-doc object doesn't make sense. Try changing your marker creation code to this:
var marker = new google.maps.Marker({
map: map,
position: latlng,
title:'pk:'+name,
zIndex: zInd,
icon: image
});
Since you have already set the value of zInd higher than google.maps.Marker.MAX_ZINDEX, making this change should place the marker higher in the zIndex and thus above the other markers on the map.
I have a map I am developing. The basic Google RED DROPLET icon shows up as my marker image. How can I get my own custom image to come up? I have individual images for just about all 50 of my markers (will be company's logo).
Can someone help? Here's the link.
Any help setting custom markers with the code I have presently would be great.
From actual code:
var image = './beachflag.png';
[...]
var marker=new google.maps.Marker({
position: myPosition,
map: map,
icon: image
});
Your code:
var point = new google.maps.LatLng(37.984798,-121.312094);
var marker = createMarker(point,'<div style="width:205px"><center><img src="images/sampleuopsign.jpg" /></center><h2>University of the Pacific</h2>3601 Pacific Avenue<br>Stockton, California 95211<br>209.946.2011<br><small>On the web visit: <a href="http://www.pacific.edu">www.Pacific.edu<\/a></small><\/div>');
var image = 'icons/orange_arrow.png'; // this will be gmarkers[0]
What you need to do:
var point = new google.maps.LatLng(37.984798,-121.312094);
var image = 'icons/orange_arrow.png'; // this will be gmarkers[0]
var marker = createMarker(point,'<div style="width:205px"><center><img src="images/sampleuopsign.jpg" /></center><h2>University of the Pacific</h2>3601 Pacific Avenue<br>Stockton, California 95211<br>209.946.2011<br><small>On the web visit: <a href="http://www.pacific.edu">www.Pacific.edu<\/a></small><\/div>', image);
And change CreateMarker:
function createMarker(latlng, html, img) {
// Note here the addition of the img parameter
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
***icon: img,***
zIndex: Math.round(latlng.lat()*-100000)<<5
});
[...]
EDIT
A quick test with your code and my mods.
You can select the image and later associated that image with your lat and long, in this case there is one function that creates the marker.
if(location.category=="TEAMNAME"){
var image='img/blueMarker.png';
}
if(location.category=="TEAMNAME2"){
var image='img/redMarker.png';
}
function displayLocation(location){
var content = '<strong><p>Team: ' +location.category + '</strong>';
var latLng = new google.maps.LatLng(parseFloat(location.latitud), parseFloat(location.longitud));
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true,
visible: true,
title: location.category,
icon: image
});
/*Content window asociated to created markers*/
google.maps.event.addListener(marker, 'click', function(){
infowindow.setContent(content);
infowindow.open(map, marker);
});
return marker;
}