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.
Related
I'm not sure the correct lingo for this, so feel free to edit the title of this post if necessary.
Basically, I'm creating a Google map object and adding a bunch of overlays, markers, etc. This is how I create the map:
map = new google.maps.Map(document.getElementById("map"), mapOptions)
But then, navigating through the side, I may land on a url where the map DOM element is destroyed, but the map object still exists in my web app. When I go back to the url that displays the map, I'd like to reattach the map to the DOM element as opposed to recreating the map.
Any ideas how to do this?
EDIT:
To be more specific, I have a bunch of markers and overlays on the map
Map =
map: null
markers:[]
icons: {}
init: ->
mapOptions =
center: new google.maps.LatLng(34.0500, -118.2500)
zoom: 9
#map = new google.maps.Map(document.getElementById("map"), mapOptions)
#icons.default =
path: google.maps.SymbolPath.CIRCLE
strokeColor: '#DD0000'
fillColor: '#DD0000'
fillOpacity: 0.6
scale:8
strokeWeight: 2
addMarker: (post) ->
gLatLng = new google.maps.LatLng post.location.lat, post.location.lng
gMarker = new google.maps.Marker
position: gLatLng
map: #map
icon: #icons.default
animation: google.maps.Animation.DROP
marker =
post: post
gMarker: gMarker
#markers.push marker
I suppose I could create a new map and attach all the markers to the new map, but this seems unnecessary because I may have many other overlays on the map
It is not possible to attach the Map object to another DOM element after the Map object has been created. As you can see in the Google Maps Javascript API v3 Reference there is only a getDiv() method available on the Map, not a setDiv().
I think you could hold on to the other objects like Marker and MapOptions to recreate the Map, but the Map object itself is useless without the corresponding DOM element.
You can create a global variable, mapOptions, where you can store the options of the map. Whenever some interaction is done with the map, you can update the mapOptions objects, and save it to localstorage.
var mapOptions = {
...
};
localStorage.setItem("mapOptions", JSON.stringify(mapOptions));
map = new google.maps.Map(document.getElementById("map"), localStorage.getItem("mapOptions"));
Hope this helps!
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.
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;
I want to clear a marker on Google Maps.
What is the difference between marker.setVisible(false) and marker.setMap(null)?
But I don't know, which is right?
The difference between the two methods does not seem to be clearly documented. However, note the following:
When you use setMap(null), your marker will lose the reference to the Map. If you do not keep a reference to the Map object, you wouldn't be able to reshow the marker.
In addition, the setMap() method will not trigger the visible_changed event, while the setVisible() method does (if the visibility is actually toggled).
Example:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(-25.363, 131.044),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-25.363, 131.044),
map: map
});
google.maps.event.addListener(marker, 'visible_changed', function() {
console.log('visible_changed triggered');
});
marker.setVisible(false); // visible_changed triggered
marker.setVisible(true); // visible_changed triggered
marker.setMap(null); // visible_changed not triggered
marker.setMap(map); // visible_changed not triggered
I guess we should be using the setVisible(false) method when we intend to reshow the marker again on the map, and the setMap(null) when we will not be showing it again.
Another key distinction is that setMap(NULL) releases the resources associated with the marker whereas setVisible(false) just makes the marker invisible, but the resources associated with the marker are still allocated.
If you're dealing with 100s or 1000s of markers, this can become a significant performance and memory issue.
I like to create a map with Google Maps that can handle large amounts of markers (over 10.000). To not slow down the map I've created a XML-file that only outputs the markers that are inside the current viewport.
First, I use initialize() to setup the map options:
function initialize() {
var myLatlng = new google.maps.LatLng(51.25503952021694,3.27392578125);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'tilesloaded', function () {
loadMapFromCurrentBounds(map);
});
}
When the event 'tilesloaded' is finished, I use loadMapFromCurrentBounds(), this functions will get the current bounds and sends a request to the XML-file to show the markers that are inside the current viewport:
function loadMapFromCurrentBounds(map) {
// First, determine the map bounds
var bounds = map.getBounds();
// Then the points
var swPoint = bounds.getSouthWest();
var nePoint = bounds.getNorthEast();
// Now, each individual coordinate
var swLat = swPoint.lat();
var swLng = swPoint.lng();
var neLat = nePoint.lat();
var neLng = nePoint.lng();
downloadUrl("mapsxml.php?swLat="+swLat+"&swLng="+swLng+"&neLat="+neLat+"&neLng="+neLng+"", function(data) {
var xml = parseXml(data);
var markers = xml.documentElement.getElementsByTagName("marker");
var infoWindow = new google.maps.InfoWindow;
for (var i = 0; i < markers.length; i++) {
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var name = markers[i].getAttribute("name");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng"))
);
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow});
bindInfoWindow(marker, map, infoWindow, html);
}
})
}
This is working great, however, the current code doesn't offload markers that aren't in de viewport anymore. Besides that, it loads markers again who are already loaded, that slows down the map really fast when moving the map a view times in the same area.
So when the viewport changes, I like to clear the whole map first before loading new markers. What is the best way to do this?
You need to add another Event Listener to the map:
google.maps.event.addListener(map,'bounds_changed', removeMarkers);
See here for more on removing all markers from a google map - unfortunately I dont think it can be done with one call. So you will have to write the removeMarkers or something similar which will have to iterate through all the markers on the map removing them individually like so:
markersArray[i].setMap(null);
I don't know whether it's quicker to check if the marker is in the viewport before removing by using:
map.getBounds();
Read more about Google Map API v3 events
Due to the following explanation using 'tilesloaded' or 'bounds_changed' would be very wrong and cause unwilling continuous firings. Instead you would want to use 'idle' event which will fire once the user has stopped panning/zooming.
google.maps.event.addListener(map, 'idle', loadMapFromCurrentBounds);
https://developers.google.com/maps/articles/toomanymarkers#viewportmarkermanagement
You may want to check out this thread. Daniel answered this quite nicely.
What's the most efficient way to create routes on google maps from gps files?
Also, bounds_changed is the first opportunity to call your function. tilesloaded, will be called constantly. The viewport may contain more than one tile to fill the viewport.
Alternatively, you can also do a setVisible(false).
In order to remove the marker, you may need to remove the listeners.
google.maps.event.clearInstanceListeners(marker);
marker.setMap(null);
markers.remove(marker);
delete marker;
This article goes through it pretty nicely:
Dynamically loading thousands of markers in Google Maps
dynamically load markers until we reach a threshold
keep a hashtable of markers that have already been added
after the threshold has been reached, remove markers that aren’t currently within the viewport
remove all markers from the map when the user has zoomed out, and don’t load any markers until the user zooms back to a reasonable level
Your original function seems like a lot of code. I'd do something like this:
if( map.getBounds().contains(markers[i].getPosition()) ) {
myMarkerDisplayFunction(markers[i]);
}
You might want to check out this documentation from Google. It explains what you need:
With the new list of markers you can remove the current markers
(marker.setMap(null)) that are on the map and
add the new ones (marker.setMap(map)).