google map kml - showing markers [duplicate] - google-maps

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

Related

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

Google maps API Basic Example

I've been unable to get the basic Google maps example working on my site. I have the following div on my page:
<div id="map_canvas" style="width:100%; height:100%"></div>
And the following in the head of my document:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
jQuery(document).ready(initialize);
</script>
It appears that the elements are getting loaded into my DOM, but there is no visible map on the page.
As per Google Map not showing up, it appears that percentage sizes on the div (e.g. 100%) don't work properly. I had to explicitly specify a pixel height and width for the div.
Use 100% only if you want to show google map on the whole screen..!!
Here is a sample which used 100% width height
http://www.rizeworkshop.com/basic-google-map-v3/
You have jQuery enabled on your site? Otherwise, within your body-tag create a "onload=initialize();"-attribut so that the javascript will be executed.
As far as I know your inital-request needs an API key?
the code looks ok and it's similar to the examples from the documentation so it should be working properly.
Have you tried printing some information on the screen from the initialize function? Check if the latlng, myoptions and map variables are created correctly.
If they are, there's a problem with calling the initialize function...
I tested your code and iw works fine if i use <body onload="initialize()"> as da_didi suggested.
Do you have an import directive for jquery.js?

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.

Access Individual Google Maps Elements (Distance, Time, Directions)

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).

Simplest way to make a Google Map mashup?

Given a list of locations such as
<td>El Cerrito, CA</td>
<td>Corvallis, OR</td>
<td>Morganton, NC</td>
<td>New York, NY</td>
<td>San Diego, CA</td>
What's the easiest way to generate a Google Map with pushpins for each location?
I'm assuming you have the basics for Maps in your code already with your API Key.
<head>
<script
type="text/javascript"
href="http://maps.google.com/maps?
file=api&v=2&key=xxxxx">
function createMap() {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.44, -122.14), 14);
}
</script>
</head>
<body onload="createMap()" onunload="GUnload()">
Everything in Google Maps is based off of latitude (lat) and longitude (lng).
So to create a simple marker you will just create a GMarker with the lat and lng.
var where = new GLatLng(37.925243,-122.307358); //Lat and Lng for El Cerrito, CA
var marker = new GMarker(where); // Create marker (Pinhead thingy)
map.setCenter(where); // Center map on marker
map.addOverlay(marker); // Add marker to map
However if you don't want to look up the Lat and Lng for each city you can use Google's Geo Coder. Heres an example:
var address = "El Cerrito, CA";
var geocoder = new GClientGeocoder;
geocoder.getLatLng(address, function(point) {
if (point) {
map.clearOverlays(); // Clear all markers
map.addOverlay(new GMarker(point)); // Add marker to map
map.setCenter(point, 10); // Center and zoom map on marker
}
});
So I would just create an array of GLatLng's of every city from the GeoCoder and then draw them on the map.
Check out the Google Maps API Examples
They make it pretty simple and their API documentation is great.
Most of the examples are for doing all the code in JavaScript on the client side, but there are APIs for other languages available as well.
I guess more information would be needed to really give you an answer, but over at Django Pluggables there is a django-googlemap plugin that might be of help.
Edit: Adam has a much better answer. When it doubt look at the API examples.
Try this: http://www.google.com/uds/solutions/wizards/mapsearch.html
It's a google maps wizard which will generate the code for you. Not the best for your application; but a good place to "get your feet wet" ;)
Edit: (found the link), here's a good Google Maps API stepwise tutorial.
Good luck!
/mp
Here are some links but as with most things i have not got round to trying them yet.
http://gathadams.com/2007/08/21/add-google-maps-to-your-net-site-in-10-minutes/
http://www.mapbuilder.net/
Cheers
John