Google Maps API v3 UNIQUE marker JS - javascript

I'm trying to have a unique marker on a simple javascript web API, no jQuery.
I first tried to delete the previous marker every time I click on the map, with
marker.setMap(null);
just before creating the new one, but it blocks the new one, nothing appears on the screen.
I can easily delete the markers with a button or other event, but is there a way to do it automatically, and have only one marker on the map (with draggable: true to move it, maybe dblClick to delete it) ?
Marker creation triggered by usual
google.maps.event.addListener(map, "click", function(event) {...
var marker = new google.maps.Marker({...
The interface is used to define a single location so I don't want more than one marker on the screen; coordinates are then saved in a database.

When you add the marker by using the var-keyword the variable will not be accessible later, the call of setMap fails(and stops the further script-execution) because of the undefined variable.
Example using a single marker(marker will be stored as property of the map):
google.maps.event.addListener(map, "click", function(event) {
//closure for the map
var that=this;
//only create a single marker
if(!this.marker){
var input = document.getElementById("location_name");
this.marker = new google.maps.Marker({draggable:true,title:input.value});
google.maps.event.addListener(this.marker,'dblclick',function(){
this.setMap(null);
});
//update title
google.maps.event
.addDomListener(input,
'change',
function(){
that.marker.setTitle(this.value);
}
);
}
//update position
this.marker.setOptions({map : this,
position : event.latLng
});
});

Related

How to open popup for a specific marker inside a leaflet MarkerClusterGroup?

I want to open a popup for a marker that is under a markercluster when the map is zoomed out. This function is called when a user clicks on a search result.
This is the code that I am using:
map.eachLayer(function (layer) {
if (layer.options && layer.options.pane === "markerPane") {
if (layer.options.title == locationId) {
layer.openPopup()
}
}
});
I tried adding this code but it didn't work as well:
layer.zoomToBounds({padding: [20, 20]});
So you want to so something about a cluster's marker whenever a specific marker in such cluster fulfills a condition.
You can iterate through all visible cluster markers, then leverage getAllChildMarkers; but that will get messy soon, as you will have to deal with the fact that a cluster and the cluster's marker are different entities, so iterating through visible markers doesn't necessarily mean iterating through the visible clusters.
I suggest an approach based on getVisibleParent. Store a reference to each original marker, indexed by the ID you'll be using later for lookup, e.g. ...
var clusterGroup = L.markerClusterGroup();
var markers = {}; // Yay using Object as a hashmap!
for (var i in dataset) {
// Create individual marker based on a item in the dataset, e.g.
var marker = L.marker(dataset[i].latlng);
// Add that to the clusterGroup (but not to the map)
clusterGroup.addMarker(marker);
// Save the individual marker in the hashmap, indexed by the
// desired property, e.g. "locationId"
markers[ dataset[i].locationId ] = marker;
}
// Adding the cluster to the map after all items have been inserted should
// be slightly more performant than doing that before.
clusterGroup.addTo(map);
So with that, one should be able to look up the marker by the desired ID, see if it's in a cluster or directly visible, and do something about it:
function highlightLocationId(id) {
// hashmap lookup
var marker = markers[i];
// Sanity check
if (!marker) { return; }
// What cluster is this marker in?
var cluster = clusterGroup.getVisibleParent(marker);
// Is the marker really in a cluster, or visible standalone?
if (cluster) {
// It's in a cluster, do something about its cluster.
cluster.openPopup();
} else {
// It's not in a cluster but directly in the map, do something about it.
marker.openPopup();
}
}
I found a fix for this issue. Before trying to open the popup in the cluster I teleport to the coordinates of the location. Then the cluster will automatically open up.
map.setView([coordinates[1], coordinates[0]], 20);
I define which coordinates should be used and what the zoom level should be. After this function I use the layer.openPopup() function to open the popup.

Getting marker from map.data class use geojson google maps

first of all I was initiate marker from geojson, and how I can get the marker if i want use marker for listener/action?
this is my script
var map;
function initMap() {
//makes map
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -6.9034482, lng: 107.6081381},
zoom: 9,
styles: [{"featureType":"water","stylers":[{"saturation":43},{"lightness":-11},{"hue":"#0088ff"}]},{"featureType":"road","elementType":"geometry.fill","stylers":[{"hue":"#ff0000"},{"saturation":-100},{"lightness":99}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"color":"#808080"},{"lightness":54}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#ece2d9"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"color":"#ccdca1"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#767676"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]},{"featureType":"poi","stylers":[{"visibility":"off"}]},{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#b8cb93"}]},{"featureType":"poi.park","stylers":[{"visibility":"on"}]},{"featureType":"poi.sports_complex","stylers":[{"visibility":"on"}]},{"featureType":"poi.medical","stylers":[{"visibility":"on"}]},{"featureType":"poi.business","stylers":[{"visibility":"simplified"}]}]
});
//load marker from geojson
map.data.loadGeoJson('<?php echo base_url().'index.php/json_site/geojsongetmap'?>');
// set style marker
map.data.setStyle(function(feature){
var tit = feature.getProperty('nm_site');
return{
title: tit,
icon: '<?php echo base_url()?>assets/images/mark3.png'
};
});
//marker event
map.data.addListener(marker, 'click', function(event) {
map.setZoom(11);
map.setCenter(marker.getPosition()); // I need to get the position of the marker who i clicked
});
}
how I can make action listener if I initiate marker from geojson?
and how I can get the marker who existing in my map?
please help me, any suggest would be appreciated
thanks
Instances of the google.maps.Data.Point class are not exactly a drop-in replacement for traditional google.maps.Marker objects. For starters, they are abstract data, not tied to a particular representation. It's up to the parent google.maps.Data layer to decide how to draw them.
However, you can still capture events, with the caveat that the click happens on the Data layer, which receives a mouseEvent as argument. This argument contains the feature over which you just clicked.
This means you need to declare:
google.maps.event.addListener(map.data,'click',function(mouseEvent) {
var clickedFeature = mouseEvent.feature,
featureGeometry = clickedFeature.getGeometry(),
featurePosition = featureGeometry.get();
map.setCenter(featurePosition);
});
Please take into consideration that ingesting geoJson with the Data layer can result not just in Point geometries. If you get a mix of points, polygons and linestrings, anything different from a point won't return a latLng object when you call its get method.

Sencha Touch 2 remove Google map Markers

i'm trying to remove all the markers from a google map using ExtJS. I'm performing a setCenter() operation (i need to remove the old center from the map) and also i want to add a new marker in the new center.
As i know, to get the google map instance i need to perform a getMap() over the map container, i.e map.getMap()
I tried with clearMarkers();, deleteMarkers(); and markers = []; but neither works. The google map object looks really weird on the Chrome Developer tools utility, at least for me.
With the addition, same problem. I'm doing that:
new google.maps.Marker({
map : map.getMap(),
position : new google.maps.LatLng(location.lat, location.lng),
title : 'Drag Marker To New Position',
animation : google.maps.Animation.DROP,
draggable : true
});
Any help is appreciated!
Thanks.
It's very simple. To remove a marker from the map, call the setMap() method passing null as the argument.
marker.setMap(null);
Note that the above method does not delete the marker. It simply removes the marker from the map. If instead you wish to delete the marker, you should remove it from the map, and then set the marker itself to null.
If you wish to manage a set of markers, you should create an array to hold the markers. Using this array, you can then call setMap() on each marker in the array in turn when you need to remove the markers. You can delete the markers by removing them from the map and then setting the array's length to 0, which removes all references to the markers.
Find an example here View example (marker-remove.html)
Read more about Google Maps Tutorial - Remove a marker
Finally i get a solution for that (maybe it's not the better way, but it works)
I decided to have a global variable that references the marker that i have to put over the map.
To define a global variable in sencha i use this approach:
Ext.application({
name: 'SIGCC',
marker: null,
....
....
});
I'm using a custom class to get an AutocompleteTextField, and when the user taps a suggested location the previous marker has to be removed and a new one is placed over the google map. Also i have to recenter the map in the new location
recenterMap: function(location){
//addressMap is the id of the xtype map component
var map = Ext.getCmp('addressMap');
map.setMapCenter({ latitude: location.lat, longitude: location.lng });
if (SIGCC.app.marker){
SIGCC.app.marker.setMap(null);
}
SIGCC.app.marker = new google.maps.Marker({
map : map.getMap(),
position : new google.maps.LatLng(location.lat, location.lng),
title : 'Drag Marker To New Position',
animation : google.maps.Animation.DROP,
draggable : true
});
//My map is hidden before de users tap action, so i have to unhide them
map.setHidden(false);
},
As you can see, this portion of code references the global variable defined previously.
Hope this helps someone.

Google Map Marker with custom numbering

I have a Google Maps marker function that successfully creates markers on a map like this:
// A function to create the marker and set up the event window
function createMarker(point,html) {
var marker = new GMarker(point,{title:html});
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
Here is a tinyurl of the exiting code: http://tinyurl.com/b8f9b4l
Using this solution: Google maps: place number in marker?
I've updated this line of code but it is not numbering. What am I doing wrong?
var marker = new GMarker(point,{title:html,icon:'icon: \'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='+ (position) +'|FF776B|000000',});
The icon property just needs to be the url. You don't need the extra "icon:", and you should drop the extra comma at the end (IE seems to throw an exception when it finds a dangling comma). Also, the parenthesis you don't need - but probably aren't hurting anything.
{
title:html,
icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=' + position +'|FF776B|000000'
}
I see where you got the idea. Idk why s/he got a point for that. The extra "icon:" messes it up.
Try this as a test, it should make sure you don't have any problems with the variables inside the url.
{
title:html,
icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=4|FF776B|000000'
}

want to get the contents of infobubble of a marker?

I am using gmap v3. I am facing a problem.
The problem is that I am creating dynamically marker and at similar time I am creating the infowindow of that marker.
Now I want to add some contents in any infowindow of a marker.
But don't know how i can get the content of a infowindow.
I have stored my markers objects in a array and also infowindow's objects.
But not found any solution.
I want to get infowindow's content on the basis of marker.
EDIT:
var markerArray = new Array();
var infoArray = new Array();
function placemarker(point,id, contents){
var marker = new google.maps.Marker({
icon: image,
position: point,
map: map,
title: name
});
markerArray[id] = marker;
var infoBubble = new InfoBubble();
var content = contents;
infoBubble.setContent(content);
google.maps.event.addListener(marker,"mouseover",function(event){
for(var i=0; i < infoArray.length ; i++ )
infoArray[i].close();
infoBubble.open(map,marker);
});
infoArray.push(infoBubble);
}
This function is called within a function many time that create marker on map.
now on a condition two markers are at same lat long and I want to show single marker with infowindow of both markers content. I have able to create single marker but not able to append the content in a info window.
If you are already keeping all the InfoWindow's in your infoArray, why don't you simply store them with the same id as you do with your markers?
var markers = {};
var infoWindows = {};
function placemarker(point, id, contents) {
var marker = ...
...
markers[id] = marker;
var infoWindow = ...
...
infoWindows[id] = infoWindow;
}
(Note that I have replaced your arrays with hashes.)
Now you can access every marker's InfoWindow (and its content via getContent()) the same way you access the marker itself.
This is pretty old but figured I would give this a shot
I'm not sure what InfoBubble is for my example I'm using InfoWindow.
function createMarker(objPoint)
{
objPoint = new google.maps.LatLng(strLat, strLng);
strFromHtml = 'Your HTML';
//creates the window with the options
objInfoWindow = new google.maps.InfoWindow(
{
content: strToHtml,
maxWidth: 250,
zIndex: -1
});
var markerOptions =
{
position: objPoint,
map: objMap
}
objMarker = new google.maps.Marker(markerOptions);
//if the marker is clicked open the window
google.maps.event.addListener(objMarker, "click", function()
{
objInfoWindow.open(objMap, objMarker);
});
}
I first create the window, then the marker, I then attach a click listener for the marker to display the infowindow on it when the marker is clicked. You could take the click out and just display it but for my purposes I wanted them to have to click it.
EDIT
Ok I've reread your question about 50 times and I hope this solution is good. As for the multiple markers in one location I don't have an answer for that. I think I have an answer for the multiple markers with its own info. If this doesn't work then you are gonna have to create an example in jsfiddle or something otherwise I don't understand what you want. Check it out here jsfiddle
When creating the infoWindow you only create it once holding default content. So put it in the initialization of the map itself. Then when creating the markers you can use the marker itself to contain the html for the infowindow to show.
var markerOptions =
{
position: objPoint,
map: objMap,
html: strHtml//added to make the marker object store the content of the infowindow
}
Then in your mouseover listener you use this.html to get the content for the infowindow
google.maps.event.addListener(objMarker, "mouseover", function()
{
objInfoWindow.setContent(this.html);
objInfoWindow.open(objMap, this);
});
As for the multiple markers in one spot. I would have to say programmatically you are gonna have to catch this and only create one marker with the content of both in one marker.
I don't think it is possible to search for a marker in a google maps (which I think is what you are trying to do).
Do you need to create two markers when they anyway are on the same point? If no I would just keep track of the infoBubbles in an array where the point coordinates is the key. So before you create a new infoBubble you check if you already have one and if that is the case you just replace it with a new combined infoBubble.
Here is a code draft.
if(infoArray[point.lat+'_'+point.lng] != undefined){
tmpBubble = infoArray[point.lat+'_'+point.lng];
infoBubble = createCombinedBubble(tmpBubble, infoBubble);
}
infoArray[point.lat+'_'+point.lng] = infoBubble;

Categories