Access Individual Google Maps Elements (Distance, Time, Directions) - google-maps

How do you access individual elements in Google Maps?
Is there a way to do this through the API or will I have to parse the DOM and pull the elements (e.g., distance, time, directions) separately? Version 2 or 3 of the API is fine.
Example:
<div jstcache="6" style="text-align: right; padding-bottom: 0.3em;"
jseval="this.innerHTML = $Route.summaryHtml">38.9 mi (about 40 mins)</div>
I want just the distance (e.g., 38.9 mi) for a Javascript calculation. If nothing exists in the API, I'll parse it out manually.
Thanks,
Mark
Note: This is the full example site I'm using: http://code.google.com/intl/en-EN/apis/maps/documentation/examples/directions-advanced.html
Update with simplified solution:
For those that need it, here is a very simple full HTML page that I was able to thin out from the example that Cannonade posted. This has all styling and other scripts removed:
<html>
<head>
<script src="maps.google.com/maps?file=api&v=2.x&a…; type="text/javascript"></script>
<script>
function initialize()
{
alert("loading ...");
if (GBrowserIsCompatible())
{
var wp = new Array ();
wp[0] = new GLatLng(32.742149,119.337218);
wp[1] = new GLatLng(32.735347,119.328485);
directions = new GDirections(); directions.loadFromWaypoints(wp);
GEvent.addListener(directions, "load", function()
{
alert(directions.getDuration().seconds);
});
}
else
{
alert("Sorry, the Google Maps API is not compatible with this browser");
}
}
</script>
</head>
<body onload="initialize();" onunload="GUnload();"></body>
</html>
Put the codesamples into index.html and you'll be set.

You you can get the individual properties of a GDirections::loadFromWaypoints request in the response.
getDuration - The duration in seconds for the travel time.
getDistance - The distance in meters or a localized string describing the distance.
You can find an example of getting the travel time here (src).

Related

google map kml - showing markers [duplicate]

I have a map on Google My Maps that I want to display using the Google Maps JavaScript API; this is so that I can easily combine multiple maps into one and create paths/markers without having to do it programmatically.
Here is the test map that I'm using. It's a cruddy map but I expect both the path and the marker to show up in my JavaScript.
https://www.google.com/maps/d/edit?mid=z_Tk3EyXNpN8.k743LUvJRr1U&usp=sharing
And here's the JavaScript:
http://jsfiddle.net/gB2YD/66/
What happens is the path I drew displays just fine, but I can't for the life of me figure out how to get the marker(s) to actually display.
<title>Google Maps API v3 : KML Layer</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<body onload="display_kmlmap()">
<div id="map_canvas" style="width:500px; height:400px; float:left">
</div>
</body>
...
function display_kmlmap()
{
// https://www.google.com/maps/d/edit?mid=z_Tk3EyXNpN8.k743LUvJRr1U&usp=sharing
var map_options = { };
var map = new google.maps.Map(document.getElementById("map_canvas"),map_options);
var kmlUrl = 'https://rawgit.com/Ravenstine/a3b18c71942a812b5b11/raw/dafd404a0410bfbc7c4ef77ef1c6437b313e8cf0/testmap.kml';
var kmlOptions = { map: map};
// Create the kmlLayer - and you are done
var kmlLayer = new google.maps.KmlLayer(kmlUrl, kmlOptions);
}
What's strange is I could swear that the markers were appearing just fine a month ago when I first attempted to do this with a proof of concept.
There seems to be a bug.
When I remove the <color/> from
Style#icon-503-DB4436-nodesc-normal>IconStyle I see the marker.
According to the documentation <color/> isn't supported at all for <IconStyle/> and will be ignored, so it shouldn't affect the rendering.
Related: Issue 8551 in the issue tracker

PlacesService and the need of html node

<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&language=pt-PT" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var request = {
placeId: 'ChIJO_PkYRozGQ0R0DaQ5L3rAAQ'
};
service = new google.maps.places.PlacesService(document.getElementById('places'));
service.getDetails(request, callback);
function callback(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log(place);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body> <div id="places"></div> </body>
</html>
I have this code that works well, but i don't know why i need to use
PlacesService(document.getElementById('some id'));
If i use only PlacesService(); I will get an error. The html_attributions is none: html_attributions: Array[0]length: 0
So, is my code fine, or what should I do?
http://jsfiddle.net/c6p14g4d/
(If you haven't figured it out 6 months later) Your code will work and should adhere to Google's policies surrounding the PlacesService.
From my understanding, "attributions" are some sort of information attributing the source of the information to a particular partner, for example, a review from Yelp (I don't know if they partner with Yelp, but that's the idea). Obviously the partner wants the end consumer of the information to know who provided it.
The idea is that when you perform a search with the PlacesService, if there is an attached map, it will render "attributions" automatically. Thus, if you don't have a map, the library will attempt to render the attributions into an html node. Hiding that node (or the map) is against the policy.
It's important to note that the html_attributions array might not always be empty in all cases when using the library, but as long as you provide a visible node in the DOM, you're fine, since the library automatically populates the node with attributions if they are there.
From the documentation, that needs to be either a HTMLDivElement or a Map:
Constructor Description
PlacesService(attrContainer:HTMLDivElement|Map) Creates a new instance of the PlacesService that renders attributions in the specified container.

Using Google Maps with Natural Earth Data Set in Fusion Tables

I am trying to create a plugin for wordpress that simply takes an array of Country Names entered in post or page creation (Much like tags), and generates a map using the Google Maps APIv3 with all of the countries highlighted (using polygon data from the natural earth data set), but I am coming up extremely short in the area of finding resources regarding how to merge these two technologies together.
I am pretty familiar with the Google Maps API and how to manipulate it within wordpress using PHP and variables provided the post object, but I can't seem to figure out how to merge it with the data provided in the natural earth data set.
I have stumbled on these, but still can't figure it out.
Country boundries using Google Map API v3
Google Maps V3: Draw German State Polygons?
http://www.geocodezip.com/geoxml3_test/v3_FusionTables_query_sidebarF_local.html?country=Germany
The last link there is VERY close to what I would want to do, except with multiple countries which is only a matter of adding more POI's in the form of countries. But I can't get this to work on my site.
Does anyone know of any good tutorials on how to do this? Or better yet, has anyone already done this type of thing with any success?
Here's what I have currently:
<head>
<script type="text/javascript"src="https://maps.googleapis.com/maps/api/&sensor=false"></script>
<script type="text/javascript">
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(27.246933444275317, 318.515625),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col38",
from: "19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA",
where: "col2 in (\x27CAN\x27, \x27MEX\x27, \x27USA\x27, \x27JPN\x27
)"
},
options: {
styleId: 9,
templateId: 8
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<head>
<body>
<div id="map-canvas" style="width: 100%; height: 400px;"></div>
</body>
Thanks,
I think you need the "IN" operator:
example
And I would suggest using the "iso" column to reduce the size of the query string.
your code works for me
Note: I did fix this "unterminated string":
where: "col2 in (\x27CAN\x27, \x27MEX\x27, \x27USA\x27, \x27JPN\x27
)"
Example allowing selection of multiple countries:
http://www.geocodezip.com/v3_FusionTables_MultiCountryBrowser.html?countries=Afghanistan,Albania,Algeria,Brazil

Integrating Spiderfier JS into markerClusterer V3 to explode multi-markers with exact same long / lat

I am using markerCLusterer V3 on a db file from Filemaker to generate a (semi-live) map of current delivery locations, based off of addresses. Grabbing the lat/long from Google and populating those
fields is no problem. Generating the map via markerClusterer is no problem. I am even hosting the JS locally so that I can change the maxZoom variable to break the clusters apart above max zoom, so that I can see multiple markers. However, with the markers at exactly the same lat / long, I can only see the last one entered. I would like to integrate OverlappingMarkerSpiderfier into this JS so that after I zoom in past the maxZoom, the markers would "spider" apart to see the markers (as an example, multiple pieces of equipment being delivered to the same address). I can't find any info here on on the web of how to do this. It's either that simple and I'm missing it or it hasn't been done yet. Thanks in advance for any help!
I'm using:
MarkerClustererPlus-2.0.14 and
OverlappingMarkerSpiderfier-version-??
At first only the clustering works, clicking on a cluster, zooms in but 2 or more markers on the exact same point still stay a cluster even when zoomed in to the maximum. Unfortunately no spiderfier showed up :-(.
But than a noticed the setMaxZoom() method on markerClusterPlus. When setting this too your appropriate zoom level (15 for me) spiderfier takes over beyond the zoom level. It looks like markerClusters says it ain't my business anymore from here on it's up to spiderfier :-).
Setting the max zoom will fix the problem:
minClusterZoom = 14;
markerCluster.setMaxZoom(minClusterZoom);
but for viewing purposes you may want to create a clusterclick listener to prevent it from zooming in really close on a cluster of points at the same location (clicking a cluster set the bounds of the map to cover the points in the cluster; if all points are at the same location it will zoom in all the way, which tends to look bad):
google.maps.event.addListener(markerCluster, 'clusterclick', function(cluster) {
map.fitBounds(cluster.getBounds()); // Fit the bounds of the cluster clicked on
if( map.getZoom() > minClusterZoom+1 ) // If zoomed in past 15 (first level without clustering), zoom out to 15
map.setZoom(minClusterZoom+1);
});
Integrating Spiderfier JS into markerClusterer
Download the oms.min.js file from here
Download the markerClusterer.js and the image folder from here
In order to make both work together you only need to add a maxZoom to the clusterMarker object
new MarkerClusterer(map, clusterMarker, {imagePath: 'images/m', maxZoom: 15});
(Zoomlevel 0 is the complete earth, and 20 is pretty close to the ground). This means that if you zoom into the map further as zoom level 15 (for example if you click on a cluster) then the clusters are not shown anymore. If you now click on markers that are on the exact same location (or close to each other) Spiderfier JS will trigger.
It follows now a minimal working example. I made some comments in the code so I think its self-explanatory, but here are some things to mention:
Replace YOUR_API_KEY with your api key
Make sure to load oms.min.js after you loaded the google maps api
Example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="https://maps.googleapis.com/maps/apijs?key=YOUR_API_KEY">
</script>
<script src="oms.min.js"></script>
<script src="markerclusterer.js"></script>
<script>
window.onload = function() {
// cluster marker
var clusterMarker = [];
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng( 50, 3),
zoom: 6,
mapTypeId: 'terrain'
});
// Create infowindow
var infoWindow = new google.maps.InfoWindow();
// Create OverlappingMarkerSpiderfier instsance
var oms = new OverlappingMarkerSpiderfier(map,
{markersWontMove: true, markersWontHide: true});
// This is necessary to make the Spiderfy work
oms.addListener('click', function(marker) {
infoWindow.setContent(marker.desc);
infoWindow.open(map, marker);
});
// Some sample data
var sampleData = [{lat:50, lng:3}, {lat:50, lng:3}, {lat:50, lng:7}];
for (var i = 0; i < sampleData.length; i ++) {
var point = sampleData[i];
var location = new google.maps.LatLng(point.lat, point.lng);
// create marker at location
var marker = new google.maps.Marker({
position: location,
map: map
});
// text to appear in window
marker.desc = "Number "+i;
// needed to make Spiderfy work
oms.addMarker(marker);
// needed to cluster marker
clusterMarker.push(marker);
}
new MarkerClusterer(map, clusterMarker, {imagePath: 'images/m', maxZoom: 15});
}
</script>
</head>
<body><div id="map" style='width:400px;height:400px;'></div></body></html>
Recommendation
If you are starting from scratch, I would recommend to use the JS Libary Leaflet. Because this library provides you with the LeafletMarkerCluster plugin which is basically markercluster with Spiderfier integrated, and a lot of other cool stuff.
Advantage:
Cluster look really nice
Leaflet really easy to use and looks pretty
You do not need to customize the code, because Spiderfier and markerCluster already integrated
Some fancy other stuff: Like showing the border on hover of a region where marker are spread.
You can freely choose your map-tiles-provider and are no longer restricted to google maps (possible providers here)
Downsites:
You may need to invest 30min to learn and use the Leaflet API instead of the Google API
If you want to use Google Map Tiles, then you need to use this plugin, because you are only allowed to use the Google Tiles when using the Google API. This plugin is a wrapper for the Google API.
Here is an example code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js"></script>
<link rel="stylesheet" href="leaflet/dist/MarkerCluster.css" />
<link rel="stylesheet" href="leaflet/dist/MarkerCluster.Default.css" />
<script src="leaflet/dist/leaflet.markercluster-src.js"></script>
<script>
$(document).ready(function(){
var tiles = L.tileLayer(***);//Depending on your tile provider
var map = new L.Map('map', {center: latlng, zoom: 1, layers: [tiles]});
var markers = new L.MarkerClusterGroup({
removeOutsideVisibleBounds: true,
spiderfyDistanceMultiplier: 2,
maxClusterRadius: 20
});
var markersList = [];
var sampleData = [{lat:50, lng:3}, {lat:50, lng:3}, {lat:50, lng:7}];
for (var i = 0; i < sampleData.length; i ++) {
var point = sampleData[i];
var location = new L.LatLng(point.lat, point.lng);
// create marker at location
var m = new L.Marker(location);
m.bindPopup("Number" +i); //Text to appear in window
markersList.push(m);
markers.addLayer(m);
}
var bounds = markers.getBounds();
map.fitBounds(bounds)
map.addLayer(markers);
}
</head>
<body><div id="map" style='width:400px;height:400px;'></div></body></html>
I came across this post because I was looking for the exact same thing, but lucky for me I have made it work!
I honestly didn't do anything special, I followed the integration guide for MarkerClusterer, and then followed the integration guide for OverlappingMarkerSpiderfier and they work flawlessly together.
When I click/zoom in on a cluster of properties that are all at the same address, initially it just shows the "top" marker, but when I click it, they Spiderfy just like you'd want them too!
What specific result are you getting when you try to use the two scripts together?
var markerClusterer = new MarkerClusterer(map, myMarkers, {
maxZoom: 15,
zoomOnClick: false
});
//zoom 0 corresponds to a map of the Earth fully zoomed out, 20 is closeup
//markerCluster goes away after zoom
//turn off zoom on click or spiderfy won't work

Is it possible to embed the sidebar with Google Maps?

We'd like to use Google Maps to keep track of local garage sales. We've created a map (see here) and we'd like to embed that map on our website. However, when we do, we lose the sidebar of the map that contains a list of all the garage sales.
We're quite familiar with how to embed a Google; they've made the process quite simple. However, is there a way that we can embed the map and keep the sidebar list of garage sales?
To my knowledge, the best way would be to create your own container of the sales and link them to a map you are populating. I am assuming you are building and entering your data on Google's site and using the embed feature, which means my answers is significantly more work.
You would need to have your down data source and use the Maps API to create a map and a sidebar.
Your woudln't be using the iFrame anymore, you would be coding your own solution. If you have done JavaScript before, it is really fairly easy, if you haven't there are some good examples.
this tutorial http://econym.org.uk/gmap/basic2.htm shows exactly how to do it and supplies the code (which i reproduce by kind permission of the authors: Community Church Javascript Team http://www.bisphamchurch.org.uk)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Google Maps</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAAPDUET0Qt7p2VcSk6JNU1sBSM5jMcmVqUpI7aqV44cW1cEECiThQYkcZUPRJn9vy_TWxWvuLoOfSFBw" type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<!-- you can use tables or divs for the overall layout -->
<table border=1>
<tr>
<td>
<div id="map" style="width: 550px; height: 450px"></div>
</td>
<td width = 150 valign="top" style="text-decoration: underline; color: #4444ff;">
<div id="side_bar"></div>
</td>
</tr>
</table>
Back to the tutorial page
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
<script type="text/javascript">
//<![CDATA[
if (GBrowserIsCompatible()) {
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
// A function to create the marker and set up the event window
function createMarker(point,name,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
return marker;
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
GEvent.trigger(gmarkers[i], "click");
}
// create the map
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng( 43.907787,-79.359741), 8);
// add the points
var point = new GLatLng(43.65654,-79.90138);
var marker = createMarker(point,"This place","Some stuff to display in the<br>First Info Window")
map.addOverlay(marker);
var point = new GLatLng(43.91892,-78.89231);
var marker = createMarker(point,"That place","Some stuff to display in the<br>Second Info Window")
map.addOverlay(marker);
var point = new GLatLng(43.82589,-78.89231);
var marker = createMarker(point,"The other place","Some stuff to display in the<br>Third Info Window")
map.addOverlay(marker);
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
}
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/
// http://econym.org.uk/gmap/
//]]>
</script>
</body>
</html>
I'm well into accessing the Google Maps API v3 with Javascript, and I've experimented successfully with a lot of different sample scripts, but I've come to the conclusion that the best (and quickest) method for producing embedded maps - with sidebars and lots of other options - is to go to http://www.mymapsplus.com/AddMyMap (thanks Chris B), and make a £10 donation to get rid of the adverts in generated maps - see e.g. http://www.hope-projects.org.uk/node/41. Their Edit page allows you to add or change almost any option you could think of with a few clicks.
What you want to do requires use of the MAPS API but it's not very hard if you know some javascript. Essentially, load the datapoints into a Javascript array, plot them on the map and then populate your html with the array information.
This link is a page I recently wrote that does the above and also dynamically repopulates the array from the db as the user drags the map (hardly any CSS at present either).
map with dynamic links
Happy to answer any more comments.
P.S. Cool map icon!
Tim
I found one site that will generate your map with a sidebar, but if you want more control, you'll need to create your own map, as the others have suggested.
http://www.mymapsplus.com/AddMyMap
http://www.mapchannels.com/
Another site that will generate your map with a sidebar is mapalist.com.