Playing around with Google Maps these days, with some directions.
I have a map that gets the directions and address (reverse-geocoding) when dragging and dropping the markers.
If there is two nodes on the map (http://dev.korebogen.dk/gmap/) the script is working fine (click set directions) - but I need to add a click event so I can place those two markers instead of hard-code the location by hand, but still be able to drag them around - or place new with new click. But I only need A to B markers.
Ive been playing around with some click events, but I can not seem to accomplish what I am looking for - hope to see some help here. Thank you very much.
This code will allow you to click and place two markers, which you can then use to load GDirections, and remove the original markers. Note that you must use this format for the query string: "from: marker#35,-25 to: marker#-20,15".
var markerArray = [];
var listener = GEvent.addListener(map, "click", function(overlay, latlng) {
var marker = new GMarker(latlng, { draggable: true });
map.addOverlay(marker);
markerArray.push(marker);
if (markerArray.length > 1) {
GEvent.removeListener(listener);
var marker1 = markerArray[0];
var marker2 = markerArray[1];
gdir.load("from: marker1#" + marker1.getLatLng() + " to: marker2#" + marker2.getLatLng());
map.removeOverlay(marker1);
map.removeOverlay(marker2);
}
});
Related
Description
I am currently working with Google Maps V3 for our client and they've asked us to implement a drawing tool that will allow them to create connected stream of lines and calculate the distance. However, it seems the Google Maps V3 Drawing Manager library is very limited in how it allows us to capture the click events for a polyline.
Our Code
google.maps.event.addListener(map, 'click', function(event){
//TODO: Store lat/long of click for distance calculation later
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
//TODO: Display the total distance of the line
});
The Goal
google.maps.event.addListener(drawingManager, 'polylineclick', function(event){
//TODO: Store lat/long of line for distance calculation and display updated distance.
});
As you can see, we want to capture the lat/long as the user is creating the polyline and display the distance as each line is created, not once the entire polyline is completed.
Also, I know we can imitate this by creating custom handlers and doing some magic with the map's click method and drawing lines manually between lat/longs, but it seems weird that the Google Maps API wouldn't have a click method for their Drawing Manager.
Clarification
The end goal is to have functionality so while drawing a polyline, we can display the total length of the polyline dynamically. I.E. I begin by drawing a line, a section appears that says "Total Line is X", I click a second spot to create a second line and the text updates to "x" + "y", I click a third and it updates to "x" + "y" + "z", etc. This is why we were hoping there is an event to handle "lineDrawn" or "polylineClick" to store these lat/longs to we can calculate the length for dynamically created lines without having the user stop drawing lines to see the total length.
Edit: Updated addListener in Our Goal to use drawingManager, not map.
Edit: Addition of Clarification section.
Basically you want to chain the two together like this:
var thePolyLine = new google.maps.Polyline({
polyLineOptions
}).setMap(map).addListener("click", function(event){
//click event
});
============= EDIT =============
Ok, I clearly didn't read the OP's question entirely.
Looks like the markercomplete event returns a marker. I'd create a global Array of marker objects, then you can run a distance check between each on catching that event.
var markers = new Array();
google.maps.event.addListener(theDrawingManager, "markercomplete", function (marker) {
markers.push(marker);
});
Then, you can loop through them, and computeDistanceBetween any or all points.
============= EDIT #2 =============
My Fiddle of the solution! (I updated the code with more comments and fixed an error, made it obvious that distance is in meters):
http://jsfiddle.net/8Xqaw/12/
Right-click the map to add points to measure.
Distance is in meters, btw. It will update distance when you drag points, too. And there is a click function for the polyLine itself.
Clicking the first point again will allow you to connect the final point with the first point to create a polygon, then you can click and drag to move the polygon around (which moves the points as well)...
Try this :3
var PolylineOption = {
strokeColor : "blue",
strokeOpacity : 0.5,
strokeWeight : 5
};
var Display;
var rendererOptions = {
draggable : true,
suppressMarkers : true,
polylineOptions : PolylineOption
};
var Service = new google.maps.DirectionsService();
Display = new google.maps.DirectionsRenderer(this.rendererOptions);
Display.setMap(map);
Service.route(this.request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
Display.setDirections(response);
}
});
google.maps.event.addListener(PolylineOption, 'click', function() {
alert(this.strokeColor);
});
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'
}
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;
Im developing an webapplication using Bing Maps V7.0
I've created a fully functional context menu, but now i want to implement it using driving directions and then i need to get the lat lon of the cursor when it's right clicked and the menu are brought up. This is how you create it in an old Bing Maps version. But it doesn't work anymore.
e.view.LatLong.Latitude
So if anyone know the new method for finding the cursor location when clicked please tell me.
It's changed to:
e.target
.tryPixelToLocation(new Microsoft.Maps.Point(e.getX(), e.getY()))
.latitude
I found the code on the MouseEventArgs documentation page:
map = new Microsoft.Maps.Map(
document.getElementById("myMap"),
{credentials:"Bing Maps Key"}
);
Microsoft.Maps.Events.addHandler(map, 'click', displayEventInfo);
// ...
function displayEventInfo(e) {
if (e.targetType == "map") {
var point = new Microsoft.Maps.Point(e.getX(), e.getY());
var loc = e.target.tryPixelToLocation(point);
document.getElementById("textBox").value = loc.latitude
+ ", " + loc.longitude;
}
}
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)).