Google Maps API not drawing polylines - google-maps

I am trying to learn how to use the Google Maps API, and I've found a lot of good tutorials. Problem is, whenever I try to implement their code into my local HTML file, I don't see any polyline drawn on my Google Map.
Here's my code (note: I do have my API key in the script at the bottom):
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body { height: 100%; margin: 0; padding: 0; }
#map { height: 100%; }
</style>
<script type="text/javascript">
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 55.500, lng: 9.000},
zoom: 10
});
}
var encoded_data = "kpgiI}{wt#{xeDfxv#ylqC|flAyfyDidPiioBoabD_fkAyjfDooZ{nyCtw_BihCnzlBzbyAl}XehjBfp`B_se#vdgAhdPya_BoabDipHoabDngiAsen#jz}#htcAzqt#itcAnha#|~eBdzh#qqnBf~w#zrlCjkx#fppAy{u#zflA{zRpeuC`zWh`]bmx#}byAlwn#ny{DncNn}nDsxd#uqG";
var decode = google.maps.geometry.encoding.decodePath(encoded_data);
var line = new google.maps.Polyline({
path: decode,
strokeColor: '#00008B',
strokeOpacity: 1.0,
strokeWeight: 4,
zIndex: 3
});
line.setMat(map);
lineArray.push(line);
</script>
</head>
<body>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?libraries=geometry,drawing&key=MY_KEY&callback=initMap">
</script>
</body>
</html>

You are loading Google Maps API using:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>
where
The async attribute lets the browser render the rest of your website
while the Maps API loads. When the API is ready, it will call the
function specified using the callback parameter
In the provided example you are trying to utilize google.maps.geometry.encoding.decodePath function but geometry library could not be loaded at this moment.
There is a typo at line:
line.setMat(map); -> line.setMap(map);
Fixed example
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 55.500, lng: 9.000 },
zoom: 7
});
var encoded_data = "kpgiI}{wt#{xeDfxv#ylqC|flAyfyDidPiioBoabD_fkAyjfDooZ{nyCtw_BihCnzlBzbyAl}XehjBfp`B_se#vdgAhdPya_BoabDipHoabDngiAsen#jz}#htcAzqt#itcAnha#|~eBdzh#qqnBf~w#zrlCjkx#fppAy{u#zflA{zRpeuC`zWh`]bmx#}byAlwn#ny{DncNn}nDsxd#uqG";
var decode = google.maps.geometry.encoding.decodePath(encoded_data);
var line = new google.maps.Polyline({
path: decode,
strokeColor: '#00008B',
strokeOpacity: 1.0,
strokeWeight: 4,
zIndex: 3
});
line.setMap(map);
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?libraries=geometry,drawing&callback=initMap">
</script>

Related

KML not shown when loaded with javascript API to google maps

I want to load a KML file with the API provided by GoogleMaps, but can't make it work.
I have a KML file that works correctly and displays all the points when loaded manually from my computer to GoogleMaps. However, when I try to do it with the API, it doesn't work. I uploaded my file to Google drive and I am using the example provided by Google (I only change coordinates, file and API key).
What am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>GeoRSS Layers</title>
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 40.45, lng: -3.8}
});
var georssLayer = new google.maps.KmlLayer({
url: 'https://drive.google.com/file/d/1rvb4xvwAZGj4gwrQLH7mjZtPBGzv97WQ',
});
georssLayer.setMap(map);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap">
</script>
</body>
</html>
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {
lat: 40.45,
lng: -3.8
}
});
var georssLayer = new google.maps.KmlLayer({
url: 'https://drive.google.com/open?id=15OVgNwtVbLVARkHJD3F8P_bEfG9oJ4Lu',
});
georssLayer.setMap(map);
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<title>GeoRSS Layers</title>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
The link to Google Drive you are using does not provide the raw KML.
If I check the status of the KmlLayer after it loads, I get INVALID_DOCUMENT (fiddle, check the javascript console)
Per the article: Direct linking to your files on Dropbox, Google Drive and OneDrive:
Google Drive direct download links
Grab the file ID from the original link (get the share link from the sharing settings) and append it to the end of the new link. With the new format, any link you share will automatically download to your recipient’s computer. For example:
https://drive.google.com/file/d/FILE_ID/edit?usp=sharing
Becomes:
https://drive.google.com/uc?export=download&id=FILE_ID
In your case:
url: 'https://drive.google.com/file/d/1rvb4xvwAZGj4gwrQLH7mjZtPBGzv97WQ',
becomes:
url: 'https://drive.google.com/uc?export=download&id=1rvb4xvwAZGj4gwrQLH7mjZtPBGzv97WQ',
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {
lat: 40.45,
lng: -3.8
}
});
var georssLayer = new google.maps.KmlLayer({
url: 'https://drive.google.com/uc?export=download&id=1rvb4xvwAZGj4gwrQLH7mjZtPBGzv97WQ',
});
google.maps.event.addListener(georssLayer, 'status_changed', function() {
console.log(georssLayer.getStatus());
})
georssLayer.setMap(map);
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>

kml not loading on ec2

I am having similar problem like this post refers to:
KML layer problems in Google Maps Javascript API v3
My kml file is not loading when hosted on my ec2 instance.
Its working when it is hosted for example on my google drive.
My ec2 port 80 is open for all and I do not block anything with iptables.
This is my html:
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 600px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
var src = "http://{my host}/locations/test.kml";
var map;
function initMap() {
var uluru = {lat: -25.363, lng: 131.044};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
loadKmlLayer(src, map);
}
function loadKmlLayer(src, map) {
var kmlLayer = new google.maps.KmlLayer(src, {
suppressInfoWindows: true,
preserveViewport: false,
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY-API-KEY&callback=initMap">
</script>
</body>
</html>
Any solutions?
This issue was finally resolved with changing the file extension from .kml to .xml as #geocodezip suggested

Collaborative Realtime Mapping with Firebase Heatmap not working

I tried the tutorial from this place.
When I get at the heatmap part it doesn't draw the map anymore.
I guess I must be doing something wrong but I have no clue...
The moment I remove the comments from icon: image part I'll get a map drawn,
but the heatmap part isn't working.
I hope that somebody can help me
Kind Regards
Guy
// Reference to the Firebase database.
var firebase = new Firebase("https://adopt-a-portal.firebaseio.com/");
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 0, lng: 0},
zoom: 3
});
// Add marker on user click
map.addListener('click', function(e) {
firebase.push({lat: e.latLng.lat(), lng: e.latLng.lng()});
});
// Create a heatmap.
var heatmap = new google.maps.visualization.HeatmapLayer({
data: [],
map: map,
radius: 8
});
firebase.on("child_added", function(snapshot, prevChildKey) {
// Get latitude and longitude from Firebase.
var newPosition = snapshot.val();
// Create a google.maps.LatLng object for the position of the marker.
// A LatLng object literal (as above) could be used, but the heatmap
// in the next step requires a google.maps.LatLng object.
var latLng = new google.maps.LatLng(newPosition.lat, newPosition.lng);
// Place a marker at that location.
var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
var marker = new google.maps.Marker({
position: latLng,
map: map
// icon: image
});
heatmap.getData().push(latLng);
});
}
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body { height: 100%; margin: 0; padding: 0; }
#map { height: 100%; }
</style>
<script src="https://cdn.firebase.com/js/client/2.2.1/firebase.js"></script>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyABc8Rw-DxVzajwPZ8C90cfFT69LfAec6o&region=BE&callback=initMap"
async defer></script>
<script src="map.js"> </script>
</body>
</html>
I get a javascript error with your code: Uncaught TypeError: Cannot read property 'HeatmapLayer' of undefined
You aren't including the visualization library.
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyABc8Rw-DxVzajwPZ8C90cfFT69LfAec6o&region=BE&callback=initMap"
async defer></script>
Should be (note the added "libraries=visualization"):
<script src="https://maps.googleapis.com/maps/api/js?libraries=visualization&key=AIzaSyABc8Rw-DxVzajwPZ8C90cfFT69LfAec6o&region=BE&callback=initMap"
async defer></script>
proof of concept fiddle

How to embed a kml or kmz file in my webpage

I need do embed a kml google earth map in my webpage.
I followed this instructions, but the link to get the code to embed doesn't seem to be activated here.
I also tryed the followning code, but it shows a simple map without the informatons in the kml file
<head>
<title></title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#google-map { height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=MY-KEY&sensor=false">
</script>
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(42.753633, 13.952404),
zoom: 10,
mapTypeId: google.maps.MapTypeId.SATELLITE,
scrollwheel: false
}
var map = new google.maps.Map(document.getElementById('google-map'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'poligono1.kml'
});
ctaLayer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
<div id="google-map" class="google-map"></div>
</body>
i put the kml file in the same folder of the webpage.
Thanks in advance for helping me!!!
i tried the scaisEdge code, and it works fine.
but in iis were missing the mime type, then i added the mime type, and now it works fine... thanks geocodezip!!!
I think this sample from google developer could be useful
<!DOCTYPE html>
<html>
<head>
<style>
#map-canvas {
width: 500px;
height: 400px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
</head>
<body>
<div id="map-canvas"></div>
<script>
/**
* #fileoverview Sample showing capturing a KML file click
* and displaying the contents in a side panel instead of
* an InfoWindow
*/
var map;
var src = 'https://developers.google.com/maps/tutorials/kml/westcampus.kml';
/**
* Initializes the map and calls the function that creates polylines.
*/
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-19.257753, 146.823688),
zoom: 2,
mapTypeId: google.maps.MapTypeId.TERRAIN
});
loadKmlLayer(src, map);
}
/**
* Adds a KMLLayer based on the URL passed. Clicking on a marker
* results in the balloon content being loaded into the right-hand div.
* #param {string} src A URL for a KML file.
*/
function loadKmlLayer(src, map) {
var kmlLayer = new google.maps.KmlLayer(src, {
suppressInfoWindows: true,
preserveViewport: false,
map: map
});
google.maps.event.addListener(kmlLayer, 'click', function(event) {
var content = event.featureData.infoWindowHtml;
var testimonial = document.getElementById('capture');
testimonial.innerHTML = content;
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>

Google Maps API Geocoding - handling multiple requests

I want to be able to reverse geocode multiple points on map. My code looks like this:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple Polylines</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas, #map_canvas {
height: 100%;
}
#media print {
html, body {
height: auto;
}
#map_canvas {
height: 650px;
}
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript" src="src/polyline.edit.packed.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
var flightPath;
var map;
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var myLatLng = new google.maps.LatLng(0, -180);
var mapOptions = {
zoom: 3,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var flightPlanCoordinates = [
/*new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
new google.maps.LatLng(-27.46758, 153.027892)*/
];
flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
// Add a listener for the click event
google.maps.event.addListener(map, 'click', addLatLng);
// Add listener for end of editing event
google.maps.event.addListener(flightPath, 'edit_end', function(path){
var coords = [];
//THIS PART IS INTERESTING FOR THIS POST
//I'm requesting geocoding for every point on map
path.forEach(function(position){
coords.push(position.toUrlValue(5));
var latlng = new google.maps.LatLng(position.lat(), position.lng());
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
console.log(results[1].formatted_address);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
window.setTimeout(console.log('tic tac'), 500);
});
console.log("[edit_end] path: " + coords.join(" | "));
});
//flightPath.setMap(map);
flightPath.edit();
}
//function when user clicked on map
function addLatLng(event) {
var path = flightPath.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear
path.push(event.latLng);
flightPath.edit();
}
// stop edit mode
function save(){
flightPath.edit(false);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(window).load(function(){
});
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
And in return I get some of the points reverse geocoded bot for some i get "Geocoder failed due to: OVER_QUERY_LIMIT", and it's not the same amount of points that pass reverse geocoding, sometimes I get 4 points processed sometimes, sometimes 5, 7 etc. Why do I get that OVER_QUERY_LIMIT error? I made maybe 100 geocoder requests today so I'm far away from 2500 day limit. If there's a better way to handle multiple requests please show it to me.