I am having issues trying to implement a dynamic marker in my OpenLayer Map widget. I would like that a marker/point is placed on the map "onclick". Instead of placing a new marker/point each mouse click, I would like the marker to be be refreshed on the new position. I have been trying to find some documentation on the layers/vectors and having difficulties understanding how to refresh/replace the layer...
Here is my current OL code for my map that updates two inputs with the latitude and longitude on mouse click:
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
],
view: new ol.View({
center: ol.proj.fromLonLat([37.41, 8.82]),
zoom: 4
})
});
map.on('click', function(evt){
var lonlat = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
var lon = lonlat[0];
var lat = lonlat[1];
document.getElementById("latitude").value = lat;
document.getElementById("longitude").value = lon;
});
Thanks in advance!
If your marker is a point feature something like this should do it
map.on('click', function(evt){
myMarker.getGeometry().setCoordinates(evt.coordinates);
});
Related
How to intercept when dommarker appears on the map?
I noticed that if the marker is not visible on the screen, there is not even its html code, I have to change a couple of styles, I need to know when they reappear
I use JavaScript API 3.0
This is a well-hidden feature which is documented here: http://developer.here.com/javascript-apis/documentation/v3/maps/topics_api_nlp/h-map-domicon.html#h-map-domicon
The idea is to add onAttach (and/or onDetach) callbacks to the DOM icon to be notified when a marker comes into the viewport using that icon. Watch out though because the DOM icon you create is always cloned before being put into a marker (because you can use the same DOM icon on multiple markers). The link should already show how it is done, but I'm adding a snippet below.
//Initialization business
var platform = new H.service.Platform({
app_id: 'DemoAppId01082013GAL',
app_code: 'AJKnXv84fjrb0KIHawS0Tg',
useCIT: true
});
var defaultLayers = platform.createDefaultLayers();
var map = new H.Map(document.getElementById('mapp'), defaultLayers.normal.map, {
center: {
lat: 52.3,
lng: 13.8
},
zoom: 10
});
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
//The onAttach function receives the DomElement, the icon object and the
//marker. The element can now be styled...
var onAttach = function(element, icon, marker) {
console.log("marker entering", element, icon, marker);
};
//Create a DomElement to use as marker icon...
var domIconEl = document.createElement("div");
domIconEl.style.width = "32px";
domIconEl.style.height = "32px";
domIconEl.style.marginLeft = "-16px";
domIconEl.style.marginTop = "-16px";
domIconEl.style.borderRadius = "20px";
domIconEl.style.background = "#006";
//Create icon with icon element adding onAttach to the options
var domIcon = new H.map.DomIcon(domIconEl, {
onAttach: onAttach
});
//Creare marker and add to map
var domMarker = new H.map.DomMarker({
lat: 52.3,
lng: 13.8
}, {
icon: domIcon
});
map.addObject(domMarker);
I have a map thats populated with markers of places from a fusion table. I'm taking the users location and displaying a circle of radius 10 miles from their location. Here is my code - http://connormccarra.com/sandbox/map/. How can I use the api to count the number of markers bound by the circle and output that number in the footer?
Cheers!
Relevant code:
var map;
function Initialize() {
var MapOptions = {
zoom: 7,
center: new google.maps.LatLng(53.4125694, -8.245014),
mapTypeId: google.maps.MapTypeId.ROADMAP,
sensor: true
};
map = new google.maps.Map(document.getElementById("map_canvas"), MapOptions);
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'Address',
from: '1OPU6utSjRYwJSFK-EXdaGmt2KgLTq2loVIjS3AA'
}
});
layer.setMap(map);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
map: map,
position: pos,
content: 'You are here!'
});
// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
map: map,
radius: 16093, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var count = mgr.getMarkerCount(circle);
document.getElementById("Address").innerHTML += count + "<BR>";
google.maps.event.addDomListener(window, 'load', initialize);
//Maps API loaded, now load customizations
var element = document.createElement('script');
element.src = 'template.js';
element.type = 'text/javascript';
var scripts = document.getElementsByTagName('script')[0];
scripts.parentNode.insertBefore(element, scripts);
}
The markers created by a FusionTableLayer are not real markers, there is no way to get them as a kind of list to filter them(you can't get any details for the markers, except you click them).
But you may request the FusionTableAPI with a spatial condition(via AJAX, jsonp is supported).
The syntax for the query:
SELECT COUNT() from tableId
WHERE ST_INTERSECTS('Address',CIRCLE(LATLNG(lat,lng),10000))
How to send a query : https://developers.google.com/fusiontables/docs/v1/sql-reference
Demo(using data of another FusionTable because your table is protected):
http://jsfiddle.net/doktormolle/bAtgf/
Simplest way: use the geometry library computeDistanceBetween method. If the distance from the user's location is less than 10 miles, the marker is in the circle.
I suggest you first fetch all the coordinates of your FusionTablesLayer.
Here is an example which was used in the sidebar
http://www.geocodezip.com/v3_FusionTables_AfricaMap_kml_sidebar.html
Then using a loop statement you can use the computeDistanceBetween function.
Detect If Marker is Within Circle Overlay
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;
}
I'm trying to do this.When a user comes to sites,i need to show him on google map and also will pass some latitude and longitude.Now my map has to show the path of user and the lat and long which i pass.
Using my below code,i pass my lat and long.Now,i need to show the user position.
How to show both this?
function initialize() {
var myOptions = {
zoom: 17,
center: new google.maps.LatLng(23.333,34.534),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var image = 'image.png';
var myLatLng = new google.maps.LatLng(23.333,34.534);
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
});
}
[This is how i tried]:http://dpaste.com/695949/
it did not work.
If you want to use HTML5 geo location then in your initialize function after you add the beachMarker put:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(e) {
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(e.coords.latitude, e.coords.longitude);
});
}, function() {
// Handle error here
});
}
To display directions on google map you need to have source and destination latlong. in your above code you have destination latlong but user latlong are missing. you need to first get user latlong then you have to use google direction renderer. for more reference read http://code.google.com/apis/maps/documentation/javascript/directions.html
user(source) latlong can be found in many ways -
using geocoder gem based on ip, address, etc.
using html5 geolocation read http://mobile.tutsplus.com/tutorials/mobile-web-apps/html5-geolocation/
I've 2 function as below:
function addMarker() {
marker = new google.maps.Marker({
position: Gpoint,
map: map,
draggable: true,
animation: google.maps.Animation.DROP
});
map.panTo(Gpoint);
google.maps.event.addListener(marker, "rightclick",
function (point) {
showContextMarker(point.latLng); } );
$('.contextmenu').remove();
};
function delMarker() { marker.setMap(null); $('.contextmenu').remove(); };
So, as may understand I have a Context Menu having "Delete Marker" option on it.
I am binding a "rightclick" listener during adding a marker, to show this menu.
Everything is working without any problem till this moment.
But when I try to click on a marker to delete; it is effecting only the last added marker.
When I try again; nothing happens.
So my idea is to get the clicked marker's id (or something that may well be useful) and run this deleting function according to this.
Briefly; I want to delete the marker that I clicked on, from a map having multiple markers.
Do you have any approach to solve this problem ?
Thanks in advance!
SOLVED!
Here is the solution. Thank you Fatih. it was impossible without your guidance:
var id;
var markers = {};
var addMarker = function () {
marker = new google.maps.Marker({
position: Gpoint,
map: map,
draggable: true,
animation: google.maps.Animation.DROP
});
map.panTo(Gpoint);
id = marker.__gm_id
markers[id] = marker;
google.maps.event.addListener(marker, "rightclick", function (point) { id = this.__gm_id; delMarker(id) });
}
var delMarker = function (id) {
marker = markers[id];
marker.setMap(null);
}
Calling delete function by: delMarker(id)
Ps: "Right clicking is enough on this case"
Thank you!
Working Sample on jsFiddle
Google Maps doesn't manage your markers. So all your markers should be managed by yourself.
Make a global marker object and push all markers to this object. And give unique id to each marker when getting a marker instance. Then when you want to delete a marker take its id and find this marker in global marker object and finally call this marker instance's setMap method with passing null argument.
Also I've added a demo that works on jsFiddle. Code is heavily documented.
Your psuedo code should be like this. For more detailed code please look the demo.
var currentId = 0;
var uniqueId = function() {
return ++currentId;
}
var markers = {};
var createMarker = function() {
var id = uniqueId(); // get new id
var marker = new google.maps.Marker({ // create a marker and set id
id: id,
position: Gpoint,
map: map,
draggable: true,
animation: google.maps.Animation.DROP
});
markers[id] = marker; // cache created marker to markers object with id as its key
return marker;
}
var deleteMarker = function(id) {
var marker = markers[id]; // find the marker by given id
marker.setMap(null);
}
Complementing the #Fatih answer you should manage the markers. For example you could add each marker in a array and then to remove, you could find this marker into the array and set the val in the map null.
Just pass your marker in the rightclick function. For example:
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: true,
title: 'Hello World!'
});
google.maps.event.addListener(marker, "rightclick", function (point) {delMarker(marker)});
And make the function look this:
var delMarker = function (markerPar) {
markerPar.setMap(null);
}
Your markers will be removeable on the rightclicks.
this worked for me:
a second currentId, if you have a better idea, let me know
var actualMarkerId = 0;
var currentId = 0;
if (actualMarkerId>0) {
deleteMarker(actualMarkerId);
console.log(actualMarkerId);
}
var id = uniqueId(); // get new id
actualMarkerId = id;
For minimal changes
var newid=0;
for (var index in results){
var marker = new google.maps.Marker({
map: map,
icon: image,
__gm_id: = newid+1,
});
}
Now marker['__gm_id'] still has a value
Simple,Use Global array for marker Objects.
Push marker object in that array on plotting marker.
Yes,We can use Id in Marker Object for Unique Reference.
Code As Below
MarkerArray = []
marker = new google.maps.Marker({
Id: 1,
position: new google.maps.LatLng(Lat,Long),
type: 'info'
});
MarkerArray.push(marker);
To remove particular Marker,Find that Element Index using Unique Id for Each Marker.
var MarkerIndex = MarkerArray.findIndex(function GetIndex(element) {
return element.Id == 1;
});
MarkerArray[MarkerIndex].setMap(null);
MarkerArray.splice(MarkerIndex, 1); // to remove element from global array