Camera tour points refresh in 3d.io - aframe

I made sortable menu of camera tour points (only jquery)
<a-entity id='cameraTour' camera tour='autoStart:false' position='21 12 -15' rotation='-35 30 0' style='display:none;'>
<a-entity class='cameraTourPoint' tour-waypoint='Front View' io3d-uuid='frontView' position='2 10 -13' rotation='-25 0 -1.5'></a-entity>
<a-entity class='cameraTourPoint' tour-waypoint='North Side View' io3d-uuid='northSideView' position='-25 8 -42' rotation='-45 -93 -1'></a-entity>
<a-entity class='cameraTourPoint' tour-waypoint='South Exit' io3d-uuid='southExit' position='24 -.8 -37.7' rotation='-2 -90 0'></a-entity>
<a-entity class='cameraTourPoint' tour-waypoint='South Angle View' io3d-uuid='southAngleView' position='21 12 -15' rotation='-35 30 0'></a-entity>
</a-entity>
For swap the camera points and menu's items i use dom manipulation functions like here:
var el = document.getElementsByClassName('cameraTourPoint')[currentItemIndex],
elBefore = document.getElementsByClassName('cameraTourPoint')[currentItemIndex+1];
document.getElementById('cameraTour').insertBefore(el,elBefore.nextSibling);
For add new way-point i made this:
var cameraTourPoint = document.createElement('a-entity'),
cameraPointAttributes = {
"id": generatePointId(),
"class": "cameraTourPoint",
"tour-waypoint": "CLEAR POINT",
"io3d-uuid": "clearPoint",
"position": function() {},
"rotation": ""
},
lastChild = document.getElementById('cameraTour').lastChild;
document.getElementById('cameraTour').insertBefore(cameraTourPoint,lastChild.nextSibling);
var clearPoint = document.getElementById('cameraTour').lastChild;
$.each(cameraPointAttributes,function(key,value){
clearPoint.setAttribute(key,value);
});
but it's not working! after swap cameraTour i want to change order and when i add new point, and trying to go to him 'onclick', i get this message:
tour.js:80 The given waypoint clearPoint does not exist. Available
waypoints: (4) ["frontView", "northSideView", "southExit",
"southAngleView"]
So, how can I refresh tour points after swapping or adding new point?
aframe 0.8.0 3d.io 1.1.x aframe-animation-component 3.2.5

probably you forgot to update the tour component
take a look at the source
https://github.com/archilogic-com/3dio-js/blob/master/src/aframe/component/tour.js
and maybe you didn't wait for the new waypoint element to be created
https://aframe.io/docs/0.7.0/core/entity.html#events
this works:
var cameraTourPoint = document.createElement('a-entity'),
cameraPointAttributes = {
"id": 'asd',
"class": "cameraTourPoint",
"tour-waypoint": "CLEAR POINT",
"io3d-uuid": "clearPoint",
"position": "-5 2 0",
"rotation": "0 0 0"
},
cameraEl = document.querySelector('[camera]'),
lastChild = cameraEl.lastChild;
cameraEl.insertBefore(cameraTourPoint,lastChild.nextSibling);
var clearPoint = cameraEl.lastChild;
$.each(cameraPointAttributes,function(key,value){
clearPoint.setAttribute(key,value);
});
// the waypoint dom element needs to be created
clearPoint.addEventListener('loaded', () => {
// update the tour component
cameraEl.components['tour'].update()
// move to target
cameraEl.components['tour'].goTo('clearPoint')
}, 100)

Related

A-Frame: parent's raycaster-intersected-cleared triggered if no intersection with children

I'm implementing a feature to get coordinate of an a-sky while moving the VR controller.
<a-scene scenelistener>
<a-sky
id="map-sky"
color="#222"
radius="700"
rotation="0 45 0"
rotation-control
raycaster-listen
class="ray-castable"
>
<a-entity
id="country-tiles"
country-tiles
scale="1 1 1"
rotation="0 90 0"
></a-entity>
</a-sky>
... // Oculus entities
</a-scene>
a-sky and its children is listening for raycasting, and print out the console logging
AFRAME.registerComponent("raycaster-listen", {
init: function() {
this.el.addEventListener("raycaster-intersected", evt => {
console.log(`raycaster ${this.el.id} intersected!!!`);
});
this.el.addEventListener("raycaster-intersected-cleared", evt => {
console.log(`raycaster ${this.el.id} cleared!!!`);
});
}
});
RESULT: while moving in and out the children country-tiles, raycaster-intersected-cleared event is triggered from the children and also its parent map-sky, mean A-Frame cannot get the intersections between a-sky and the raycasting VR controller.
raycaster intersected!!!
raycaster map-sky intersected!!!
// Moving out the tile
raycaster cleared!!!
raycaster map-sky cleared!!!
You can check on this Glitch
NOTE: since I am developing for VR controller, therefore please use the WebXR emulator extension for interaction
It turns out that raycaster-intersected-cleared event from parent element is fired but it does not mean that it is not intersected anymore. To confirm if it has been still intersected I have to check if getIntersection result is NULL.
AFRAME.registerComponent("raycaster-listen", {
init: function() {
this.el.addEventListener("raycaster-intersected", evt => {
console.log(`raycaster ${this.el.id} intersected!!!`);
this.raycaster = evt.detail.el;
});
this.el.addEventListener("raycaster-intersected-cleared", evt => {
if (this.raycaster) {
const intersection = this.raycaster.components.raycaster.getIntersection(this.el);
if (!intersection) {
console.log(`raycaster ${this.el.id} cleared!!!`);
}
}
});
}
});

Add link to GLTF object in aframe

Is it possible to add a link to an GLTF 3d object (which is triggered with a marker?)
I've tried the usual 'a-link' method, the onClick method, even applying an id and using jQuery - all without luck - any help would be appreciated.
<a-scene embedded arjs>
<a-marker id="dragon" preset="custom" type="pattern" url="pattern-dragonfly.patt">
<a-entity animation-mixer="clip: *;" scale="1.5 1.5 1.5" gltf-model-next="src: url(dragon.gltf);"></a-entity>
</a-marker>
<a-entity camera></a-entity>
</a-scene>
To make this work, you need to create a cursor with a raycaster, and a custom component for the gltf.
<a-entity id="mouseCursor" cursor="rayOrigin: mouse" raycaster="objects: .clickable"></a-entity>
<a-entity id="tree" gltf-model="#gltftree" scale="5 5 5" treeman class="clickable" ></a-entity>
Inside the custom component, first you traverse the gltf and store references to the models that you want to be interactive, like this
init: function(){
let el = this.el;
let self = this;
self.trees = [];
el.addEventListener("model-loaded", e =>{
let tree3D = el.getObject3D('mesh');
if (!tree3D){return;}
console.log('tree3D', tree3D);
tree3D.traverse(function(node){
if (node.isMesh){
console.log(node);
self.trees.push(node);
node.material = new THREE.MeshStandardMaterial({color: 0x33aa00});
}
});
});
Then you make event listeners that detect intersection events, and save which object has been intersected, and highlight it, so users know it is live, like this
el.addEventListener('raycaster-intersected', e =>{
self.raycaster = e.detail.el;
let intersection = self.raycaster.components.raycaster.getIntersection(el);
console.log('click', intersection.object.name, self.mouseOverObject,
intersection.object.name != self.mouseOverObject );
if (self.mouseOverObject != intersection.object.name){
intersection.object.material.emissive = new THREE.Color(0xFFFF00);
intersection.object.material.emissiveIntensity = 0.5;
} else {
intersection.object.material.emissive = new THREE.Color(0x000000);
intersection.object.material.emissiveIntensity = 0.0;
}
self.mouseOverObject = intersection.object.name;
});
el.addEventListener('raycaster-intersected-cleared', e =>{
self.trees.forEach(function(tree){
tree.material.emissive = new THREE.Color(0x000000);
tree.material.emissiveIntensity = 0.0;
});
self.mouseOverObject = null;
});
Finally add a click listener that operate the hyperlink, like this
el.addEventListener('click', function(){
console.log(self.mouseOverObject);
if(self.mouseOverObject === "Trunk_A"){
console.log('link');
let url = 'https://supermedium.com/supercraft/';
let win = window.open(url, '_blank');
win.focus();
}
});
glitch here
Click the trunk to activate the hyperlink.

Handling GearVR Controller events in AFrame

So, I should start out with the warning that I'm new to AFrame, (though not to programming, game programming, or Javascript). I'm currently trying to put together a simple scene with basic GearVR controller interaction.
When I say "basic interaction", I mean I have the little starter scene that you get when you follow the official tutorial, and I'm just trying to expand that out, such that when you press the trigger, (and specifically the trigger, not just any button), the little text component has it's text value changed.
To make a long story short -- my code isn't working. Despite the fact that I add the event listener in the component init function, (and I've confirmed that init is being called), the listener callback never seems to be invoked. If I had to guess, I'd say that the entity I've attached 'laser-controls' to isn't emitting the 'triggerdown' event, but I'm not sure how to confirm that. Here are the relevant pieces:
AFRAME.registerComponent('gearvr-trigger', {
schema: {
textValue: {
default: "Hello WebVR!"
}
},
init: function() {
var message_box = document.querySelector('#message');
var el = this.el;
el.addEventListener('triggerdown', function(evt) {
message_box.setAttribute('value', this.data.textValue);
});
}
});
<a-text id='message' value="Hello, A-Frame!" color="#BBB"
position="-0.9 0.2 -3" scale="1.5 1.5 1.5">
</a-text>
<a-box gearvr-trigger='textValue: "New Text Value";' src='#boxTexture' position='0 2 -5' rotation='0 45 45' scale='2 2 2'>
<a-animation attribute='position' to='0 2.5 -5' direction='alternate' dur='2000' repeat='indefinite'></a-animation>
<a-animation attribute="scale" begin="mouseenter" dur="300" to="2.3 2.3 2.3"></a-animation>
<a-animation attribute="scale" begin="mouseleave" dur="300" to="2 2 2"></a-animation>
<a-animation attribute="rotation" begin="click" dur="2000" to="360 405 45"></a-animation>
</a-box>
<a-entity raycaster='far: 100; showLine: true;' line='color: red;' laser-controls></a-entity>
If someone with more experience than me sees what I'm doing wrong, that would be great, but I'd also be happy if you could just point me at some decent code examples of responding to GearVR controller events.
As others have noted, the reason you're not picking up the 'triggerdown' events in your custom component is that these events are emitted by the controller entity (a-entity[laser-controls] in this case), and they bubble just as in the standard DOM, (which would be next to a-scene in this case), so a-box is not seeing them.
When you combine information about controller buttons and the controller's relation to other entities in the scene (e.g. pointing with a laser or collisions), I like to call that a gesture. The laser-controls component provides basic gesture interpretation, but I have created the super-hands package for rich gesture interpretation including what you require: button discrimination.
<html>
<head>
<script src="https://aframe.io/releases/0.7.1/aframe.min.js"></script>
<script src="https://unpkg.com/super-hands/dist/super-hands.min.js"></script>
<script>
AFRAME.registerComponent('gearvr-trigger', {
schema: {
textValue: {
default: "Hello WebVR!"
}
},
init: function() {
var message_box = document.querySelector('#message');
var el = this.el;
var triggerResponse = function (evt) {
if (evt.detail.state === 'clicked') {
message_box.setAttribute('value', this.data.textValue);
}
}
el.addEventListener('stateadded', triggerResponse.bind(this));
}
});
</script>
</head>
<body>
<a-scene>
<a-assets>
<a-mixin id="point-laser" raycaster='far: 100; showLine: true;' line='color: red;'></a-mixin>
</a-assets>
<a-text id='message' value="Hello, A-Frame!" color="#BBB"
position="-0.9 0.2 -3" scale="1.5 1.5 1.5">
</a-text>
<a-box clickable="startButtons: triggerdown, mousedown; endButtons: triggerup, mouseup" gearvr-trigger='textValue: "New Text Value";' src='#boxTexture' position='0 2 -5' rotation='0 45 45' scale='2 2 2'>
<a-animation attribute='position' to='0 2.5 -5' direction='alternate' dur='2000' repeat='indefinite'></a-animation>
<a-animation attribute="scale" begin="hover-start" dur="300" to="2.3 2.3 2.3"></a-animation>
<a-animation attribute="scale" begin="hover-end" dur="300" to="2 2 2"></a-animation>
<a-animation attribute="rotation" begin="grab-end" dur="2000" to="360 405 45"></a-animation>
</a-box>
<a-entity progressive-controls="maxLevel: point; pointMixin: point-laser" ></a-entity>
</a-scene>
</body>
</html>
For the controller, progressive-controls auto-detects the controller and sets up the laser pointer like laser-controls, but using super-hands gesture interpretation (it also provides cursor-like input for desktop/cardboard users).
<a-entity progressive-controls="maxLevel: point; pointMixin: point-laser"></a-entity>
For the target entity, clickable activates it as a gesture receiving component and defines which button events it will accept (you can remove the mouse ones if you don't want cross-platform support). The animation trigger events were also updatedaa to work with super-hands.
<a-box clickable="startButtons: triggerdown, mousedown; endButtons: triggerup, mouseup" gearvr-trigger='textValue: "New Text Value";' ...>
...
<a-animation attribute="scale" begin="hover-start" dur="300" to="2.3 2.3 2.3"></a-animation>
<a-animation attribute="scale" begin="hover-end" dur="300" to="2 2 2"></a-animation>
<a-animation attribute="rotation" begin="grab-end" dur="2000" to="360 405 45"></a-animation>
For your custom reaction component, I changed it to react to state changes, which is how clickable communicates that is has received an acceptable gesture. I also resolved a scoping issue that you would have caught once you had the events triggering this.
var triggerResponse = function (evt) {
if (evt.detail.state === 'clicked') {
message_box.setAttribute('value', this.data.textValue);
}
}
el.addEventListener('stateadded', triggerResponse.bind(this));
Try setAttribute('text', 'value, 'whatever you wanted') ?
In case it's not the trigger code, it could be a scope issue:
'this' is referring to the element in the handler as opposed to the component, so this.data is undefined during the event
A potential fix:
AFRAME.registerComponent('gearvr-trigger', {
schema: {
textValue: {
default: "Hello WebVR!"
}
},
init: function() {
var message_box = document.querySelector('#message');
var el = this.el;
var self = this;
el.addEventListener('triggerdown', function(evt) {
message_box.setAttribute('value', self.data.textValue);
});
}
});
or using an arrow function
AFRAME.registerComponent('gearvr-trigger', {
schema: {
textValue: {
default: "Hello WebVR!"
}
},
init: function() {
var message_box = document.querySelector('#message');
var el = this.el;
el.addEventListener('triggerdown', (evt) => {
message_box.setAttribute('value', this.data.textValue);
});
}
});
The triggerdown event fires on the entity with the laser-controls attribute.
My code uses the click event and responds to either button press (unlike what you want) but implementing this pattern may nudge you forward. (It's also more on the path to cross-device operation.) The click event may contain which button was pressed.
In the scene, I have:
<a-entity laser-controls="hand: right"></a-entity>
In a script, I register
AFRAME.registerComponent('cursor-listener', {
init: function () {
var lastIndex = -1;
var COLORS = ['purple', 'orange', 'white'];
this.el.addEventListener('click', function (evt) {
lastIndex = (lastIndex + 1) % COLORS.length;
this.setAttribute('material', 'color', COLORS[lastIndex]);
console.log('I was clicked at: ', evt.detail.intersection.point);
});
}
});
Then I set the cursor-listener attribute on the target boxes:
boxEl.setAttribute('cursor-listener', true);

OpenLayers: display remote kml

I'm trying to let OpenLayers display a KML file that was retrieved from a server.
For some reason this does not work.
Similar questions have been asked, but I could not find a working example.
What I did was improve one of the examples in the OpenLayers distribution: kml-track.js
I improved it with what I found. This is what it looks like. I feel like I'm missing something obvious.
Any pointers are welcome
var map ;
function init() {
var mercator = new OpenLayers.Projection("EPSG:900913");
var geographic = new OpenLayers.Projection("EPSG:4326");
//note that I have host equal to location// //Math.Random will stop caching//
var mykmlurl = 'http://myserver/kml-track.kml';
map = new OpenLayers.Map({
div: "map",
projection: mercator,
layers: [
new OpenLayers.Layer.OSM(),
//Defiine your KML layer//
new OpenLayers.Layer.Vector("This Is My KML Layer", {
//Set your projection and strategies//
projection: geographic,
strategies: [new OpenLayers.Strategy.Fixed()],
//set the protocol with a url//
protocol: new OpenLayers.Protocol.HTTP({
//set the url to your variable//
url: mykmlurl,
//format this layer as KML//
format: new OpenLayers.Format.KML({
//maxDepth is how deep it will follow network links//
maxDepth: 1,
//extract styles from the KML Layer//
extractStyles: true,
//extract attributes from the KML Layer//
extractAttributes: true
})
}),
styleMap: new OpenLayers.StyleMap({
"default": new OpenLayers.Style({
graphicName: "circle",
pointRadius: 2,
fillOpacity: 0.5,
fillColor: "#ffcc66",
strokeColor: "#666633",
strokeWidth: 1
})
})
})
],
center: new OpenLayers.LonLat(-93.2735, 44.8349).transform(geographic, mercator),
zoom: 8
});
//function called// //timer// //layer to refresh//
window.setInterval(UpdateKmlLayer, 5000, MyKmlLayer);
}
function UpdateKmlLayer(layer) {
//setting loaded to false unloads the layer//
layer.loaded = false;
//setting visibility to true forces a reload of the layer//
layer.setVisibility(true);
//the refresh will force it to get the new KML data//
layer.refresh({ force: true, params: { 'key': Math.random()} });
}
This is an example of how to display a KML layer in OpenLayers which might help you:
http://openlayers.org/dev/examples/kml-layer.html
Are you getting any errors when opening your page - or does it run ok but nothing appear? If you're not getting any errors then it might indicate an issue with how your projections are set up (i.e. your features might not appear where you expect them to)

Google Maps API 3 - Custom marker color for default (dot) marker

I've seen lots of other questions similar to this (here, here and here), but they all have accepted answers that don't solve my problem. The best solution I have found to the problem is the StyledMarker library, which does let you define custom colours for markers, but I can't get it to use the default marker (the one you get when you do a google maps search - with a dot in the middle), it just seems to provide markers with a letter in, or with a special icon.
You can dynamically request icon images from the Google charts api with the urls:
http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FE7569
Which looks like this: the image is 21x34 pixels and the pin tip is at position (10, 34)
And you'll also want a separate shadow image (so that it doesn't overlap nearby icons):
http://chart.apis.google.com/chart?chst=d_map_pin_shadow
Which looks like this: the image is 40x37 pixels and the pin tip is at position (12, 35)
When you construct your MarkerImages you need to set the size and anchor points accordingly:
var pinColor = "FE7569";
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
new google.maps.Size(40, 37),
new google.maps.Point(0, 0),
new google.maps.Point(12, 35));
You can then add the marker to your map with:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(0,0),
map: map,
icon: pinImage,
shadow: pinShadow
});
Simply replace "FE7569" with the color code you're after. Eg:
Credit due to Jack B Nimble for the inspiration ;)
If you use Google Maps API v3 you can use setIcon e.g.
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
Or as part of marker init:
marker = new google.maps.Marker({
icon: 'http://...'
});
Other colours:
Blue marker
Red marker
Purple marker
Yellow marker
Green marker
Use the following piece of code to update default markers with different colors.
(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)
Here is a nice solution using the Gooogle Maps API itself. No external service, no extra library. And it enables custom shapes and multiple colors and styles. The solution uses vectorial markers, which googlemaps api calls Symbols.
Besides the few and limited predefined symbols, you can craft any shape of any color by specifying an SVG path string (Spec).
To use it, instead of setting the 'icon' marker option to the image url, you set it to a dictionary containing the symbol options. As example, I managed to craft one symbol that is quite similar to the standard marker:
function pinSymbol(color) {
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 M -2,-30 a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0',
fillColor: color,
fillOpacity: 1,
strokeColor: '#000',
strokeWeight: 2,
scale: 1,
};
}
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(latitude, longitude),
icon: pinSymbol("#FFF"),
});
I you are careful to keep the shape key point at 0,0 you avoid having to define marker icon centering parameters. Another path example, the same marker without the dot:
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',
And here you have a very simple and ugly coloured flag:
path: 'M 0,0 -1,-2 V -43 H 1 V -2 z M 1,-40 H 30 V -20 H 1 z',
You can also create the paths using a visual tool like Inkscape (GNU-GPL, multiplatform). Some useful hints:
Google API just accepts a single path, so you have to turn any other object (square, cercle...) into a path and join them as a single one. Both commands at the Path menu.
To move the path to the (0,0), go to the Path Edit mode (F2) select all
the control nodes and drag them. Moving the object with F1, won't change the path node coords.
To ensure the reference point is at (0,0), you can select it alone and edit the coords by hand on the top toolbar.
After saving the SVG file, which is an XML, open it with an editor, look for the svg:path element and copy the content of the 'd' attribute.
Well the closest thing I've been able to get with the StyledMarker is this.
The bullet in the middle isn't quite a big as the default one though. The StyledMarker class simply builds this url and asks the google api to create the marker.
From the class use example use "%E2%80%A2" as your text, as in:
var styleMaker2 = new StyledMarker({styleIcon:new StyledIcon(StyledIconTypes.MARKER,{text:"%E2%80%A2"},styleIconClass),position:new google.maps.LatLng(37.263477473067, -121.880502070713),map:map});
You will need to modifiy StyledMarker.js to comment out the lines:
if (text_) {
text_ = text_.substr(0,2);
}
as this will trim the text string to 2 characters.
Alternatively you could create custom marker images based on the default one with the colors you desire and override the default marker with code such as this:
marker = new google.maps.Marker({
map:map,
position: latlng,
icon: new google.maps.MarkerImage(
'http://www.gettyicons.com/free-icons/108/gis-gps/png/24/needle_left_yellow_2_24.png',
new google.maps.Size(24, 24),
new google.maps.Point(0, 0),
new google.maps.Point(0, 24)
)
});
I've extended vokimon's answer a bit, making it a bit more convenient for changing other properties as well.
function customIcon (opts) {
return Object.assign({
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 M -2,-30 a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0',
fillColor: '#34495e',
fillOpacity: 1,
strokeColor: '#000',
strokeWeight: 2,
scale: 1,
}, opts);
}
Usage:
marker.setIcon(customIcon({
fillColor: '#fff',
strokeColor: '#000'
}));
Or when defining a new marker:
const marker = new google.maps.Marker({
position: {
lat: ...,
lng: ...
},
icon: customIcon({
fillColor: '#2ecc71'
}),
map: map
});
Hi you can use icon as SVG and set colors. See this code
/*
* declare map and places as a global variable
*/
var map;
var places = [
['Place 1', "<h1>Title 1</h1>", -0.690542, -76.174856,"red"],
['Place 2', "<h1>Title 2</h1>", -5.028249, -57.659052,"blue"],
['Place 3', "<h1>Title 3</h1>", -0.028249, -77.757507,"green"],
['Place 4', "<h1>Title 4</h1>", -0.800101286, -76.78747820,"orange"],
['Place 5', "<h1>Title 5</h1>", -0.950198, -78.959302,"#FF33AA"]
];
/*
* use google maps api built-in mechanism to attach dom events
*/
google.maps.event.addDomListener(window, "load", function () {
/*
* create map
*/
var map = new google.maps.Map(document.getElementById("map_div"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
/*
* create infowindow (which will be used by markers)
*/
var infoWindow = new google.maps.InfoWindow();
/*
* create bounds (which will be used auto zoom map)
*/
var bounds = new google.maps.LatLngBounds();
/*
* marker creater function (acts as a closure for html parameter)
*/
function createMarker(options, html) {
var marker = new google.maps.Marker(options);
bounds.extend(options.position);
if (html) {
google.maps.event.addListener(marker, "click", function () {
infoWindow.setContent(html);
infoWindow.open(options.map, this);
map.setZoom(map.getZoom() + 1)
map.setCenter(marker.getPosition());
});
}
return marker;
}
/*
* add markers to map
*/
for (var i = 0; i < places.length; i++) {
var point = places[i];
createMarker({
position: new google.maps.LatLng(point[2], point[3]),
map: map,
icon: {
path: "M27.648 -41.399q0 -3.816 -2.7 -6.516t-6.516 -2.7 -6.516 2.7 -2.7 6.516 2.7 6.516 6.516 2.7 6.516 -2.7 2.7 -6.516zm9.216 0q0 3.924 -1.188 6.444l-13.104 27.864q-0.576 1.188 -1.71 1.872t-2.43 0.684 -2.43 -0.684 -1.674 -1.872l-13.14 -27.864q-1.188 -2.52 -1.188 -6.444 0 -7.632 5.4 -13.032t13.032 -5.4 13.032 5.4 5.4 13.032z",
scale: 0.6,
strokeWeight: 0.2,
strokeColor: 'black',
strokeOpacity: 1,
fillColor: point[4],
fillOpacity: 0.85,
},
}, point[1]);
};
map.fitBounds(bounds);
});
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map_div" style="height: 400px;"></div>
since version 3.11 of the google maps API, the Icon object replaces MarkerImage. Icon supports the same parameters as MarkerImage. I even found it to be a bit more straight forward.
An example could look like this:
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
for further information check this site
As others have mentioned, vokimon's answer is great but unfortunately Google Maps is a bit slow when there are many SymbolPath/SVG-based markers at once.
It looks like using a Data URI is much faster, approximately on par with PNGs.
Also, since it's a full SVG document, it's possible to use a proper filled circle for the dot. The path is modified so it is no longer offset to the top-left, so the anchor needs to be defined.
Here's a modified version that generates these markers:
var coloredMarkerDef = {
svg: [
'<svg viewBox="0 0 22 41" width="22px" height="41px" xmlns="http://www.w3.org/2000/svg">',
'<path d="M 11,41 c -2,-20 -10,-22 -10,-30 a 10,10 0 1 1 20,0 c 0,8 -8,10 -10,30 z" fill="{fillColor}" stroke="#ffffff" stroke-width="1.5"/>',
'<circle cx="11" cy="11" r="3"/>',
'</svg>'
].join(''),
anchor: {x: 11, y: 41},
size: {width: 22, height: 41}
};
var getColoredMarkerSvg = function(color) {
return coloredMarkerDef.svg.replace('{fillColor}', color);
};
var getColoredMarkerUri = function(color) {
return 'data:image/svg+xml,' + encodeURIComponent(getColoredMarkerSvg(color));
};
var getColoredMarkerIcon = function(color) {
return {
url: getColoredMarkerUri(color),
anchor: coloredMarkerDef.anchor,
size: coloredMarkerDef.size,
scaledSize: coloredMarkerDef.size
}
};
Usage:
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(latitude, longitude),
icon: getColoredMarkerIcon("#FFF")
});
The downside, much like a PNG image, is the whole rectangle is clickable. In theory it's not too difficult to trace the SVG path and generate a MarkerShape polygon.
In Internet Explorer, this solution does not work in ssl.
One can see the error in console as:
SEC7111: HTTPS security is compromised by this,
Workaround : As one of the user here suggested replace
chart.apis.google.com to chart.googleapis.com for the URL path to avoid SSL error.
You can use this code it works fine.
var pinImage = new google.maps.MarkerImage("http://www.googlemapsmarkers.com/v1/009900/");<br>
var marker = new google.maps.Marker({
position: yourlatlong,
icon: pinImage,
map: map
});
Combine a symbol-based marker whose path draws the outline, with a '●' character for the center. You can substitute the dot with other text ('A', 'B', etc.) as desired.
This function returns options for a marker with the a given text (if any), text color, and fill color. It uses the text color for the outline.
function createSymbolMarkerOptions(text, textColor, fillColor) {
return {
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: fillColor,
fillOpacity: 1,
strokeColor: textColor,
strokeWeight: 1.8,
labelOrigin: { x: 0, y: -30 }
},
label: {
text: text || '●',
color: textColor
}
};
}
I try two ways to create the custom google map marker, this run code used canvg.js is the best compatibility for browser.the Commented-Out Code is not support IE11 urrently.
var marker;
var CustomShapeCoords = [16, 1.14, 21, 2.1, 25, 4.2, 28, 7.4, 30, 11.3, 30.6, 15.74, 25.85, 26.49, 21.02, 31.89, 15.92, 43.86, 10.92, 31.89, 5.9, 26.26, 1.4, 15.74, 2.1, 11.3, 4, 7.4, 7.1, 4.2, 11, 2.1, 16, 1.14];
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {
lat: 59.325,
lng: 18.070
}
});
var markerOption = {
latitude: 59.327,
longitude: 18.067,
color: "#" + "000",
text: "ha"
};
marker = createMarker(markerOption);
marker.setMap(map);
marker.addListener('click', changeColorAndText);
};
function changeColorAndText() {
var iconTmpObj = createSvgIcon( "#c00", "ok" );
marker.setOptions( {
icon: iconTmpObj
} );
};
function createMarker(options) {
//IE MarkerShape has problem
var markerObj = new google.maps.Marker({
icon: createSvgIcon(options.color, options.text),
position: {
lat: parseFloat(options.latitude),
lng: parseFloat(options.longitude)
},
draggable: false,
visible: true,
zIndex: 10,
shape: {
coords: CustomShapeCoords,
type: 'poly'
}
});
return markerObj;
};
function createSvgIcon(color, text) {
var div = $("<div></div>");
var svg = $(
'<svg width="32px" height="43px" viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">' +
'<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>' +
'<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>' +
'<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>' +
'</svg>'
);
div.append(svg);
var dd = $("<canvas height='50px' width='50px'></cancas>");
var svgHtml = div[0].innerHTML;
//todo yao gai bu dui
canvg(dd[0], svgHtml);
var imgSrc = dd[0].toDataURL("image/png");
//"scaledSize" and "optimized: false" together seems did the tricky ---IE11 && viewBox influent IE scaledSize
//var svg = '<svg width="32px" height="43px" viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">'
// + '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>'
// + '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>'
// + '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>'
// + '</svg>';
//var imgSrc = 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
var iconObj = {
size: new google.maps.Size(32, 43),
url: imgSrc,
scaledSize: new google.maps.Size(32, 43)
};
return iconObj;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Your Custom Marker </title>
<style>
/* 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;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://canvg.github.io/canvg/canvg.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
</body>
</html>
I tried for a long time to improve vokimon's drawn marker and make it more similar to Google Maps one (and pretty much succeeded). This is the code I got:
let circle=true;
path = 'M 0,0 C -0.7,-9 -3,-14 -5.5,-18.5 '+
'A 16,16 0 0,1 -11,-29 '+
'A 11,11 0 1,1 11,-29 '+
'A 16,16 0 0,1 5.5,-18.5 '+
'C 3,-14 0.7,-9 0,0 z '+
['', 'M -2,-28 '+
'a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0'][new Number(circle)];
I also scaled it by 0.8.
These are custom Circular markers
small_red:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAiklEQVR42mNgQIAoIF4NxGegdCCSHAMzEC+NUlH5v9rF5f+ZoCAwHaig8B8oPhOmKC1NU/P//7Q0DByrqgpSGAtSdOCAry9WRXt9fECK9oIUPXwYFYVV0e2ICJCi20SbFAuyG5uiECUlkKIQmOPng3y30d0d7Lt1bm4w301jQAOgcNoIDad1yOEEAFm9fSv/VqtJAAAAAElFTkSuQmCC
small_yellow:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAi0lEQVR42mNgQIAoIF4NxGegdCCSHAMzEC+NijL7v3p1+v8zZ6rAdGCg4X+g+EyYorS0NNv////PxMCxsRYghbEgRQcOHCjGqmjv3kKQor0gRQ8fPmzHquj27WaQottEmxQLshubopAQI5CiEJjj54N8t3FjFth369ZlwHw3jQENgMJpIzSc1iGHEwB8p5qDBbsHtAAAAABJRU5ErkJggg==
small_green:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAiElEQVR42mNgQIAoIF4NxGegdCCSHAMzEC81izL7n746/X/VmSowbRho+B8oPhOmKM02zfb/TCzQItYCpDAWpOhA8YFirIoK9xaCFO0FKXrY/rAdq6Lm280gRbeJNikWZDc2RUYhRiBFITDHzwf5LmtjFth3GesyYL6bxoAGQOG0ERpO65DDCQDX7ovT++K9KQAAAABJRU5ErkJggg==
small_blue:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAiklEQVR42mNgQIAoIF4NxGegdCCSHAMzEC81M4v6n56++n9V1RkwbWgY+B8oPhOmKM3WNu3/zJn/MbCFRSxIYSxI0YHi4gNYFRUW7gUp2gtS9LC9/SFWRc3Nt0GKbhNtUizIbmyKjIxCQIpCYI6fD/JdVtZGsO8yMtbBfDeNAQ2AwmkjNJzWIYcTAMk+i9OhipcQAAAAAElFTkSuQmCC
small_purple:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAi0lEQVR42mNgQIAoIF4NxGegdCCSHAMzEC+NMov6vzp99f8zVWfAdKBh4H+g+EyYorQ027T//2f+x8CxFrEghbEgRQcOFB/Aqmhv4V6Qor0gRQ8ftj/Equh2822QottEmxQLshubohCjEJCiEJjj54N8tzFrI9h36zLWwXw3jQENgMJpIzSc1iGHEwBt95qDejjnKAAAAABJRU5ErkJggg==
They are 9x9 png images.
Once they're on your page you can just drag them off and you'll have the actual png file.
change it to chart.googleapis.com for the path, otherwise SSL won't work
Using swift and Google Maps Api v3, this was the easiest way I was able to do it:
icon = GMSMarker.markerImageWithColor(UIColor.blackColor())
hope it helps someone.
Sometimes something really simple, can be answered complex. I am not saying that any of the above answers are incorrect, but I would just apply, that it can be done as simple as this:
I know this question is old, but if anyone just wants to change to pin or marker color, then check out the documentation: https://developers.google.com/maps/documentation/android-sdk/marker
when you add your marker simply set the icon-property:
GoogleMap gMap;
LatLng latLng;
....
// write your code...
....
gMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
There are 10 default colors to choose from. If that isn't enough (the simple solution) then I would probably go for the more complex given in the other answers, fulfilling a more complex need.
ps: I've written something similar in another answer and therefore I should refer to that answer, but the last time I did that, I was asked to post the answer since it was so short (as this one)..
You can use color code also.
const marker: Marker = this.map.addMarkerSync({
icon: '#008000',
animation: 'DROP',
position: {lat: 39.0492127, lng: -111.1435662},
map: this.map,
});

Resources