Google maps - storing application-defined data in path - javascript

In my app I want to store application-defined data on each latLng in a path.
I have got this to work using the code example below, but I would like to know whether this is an undocumented fluke that just 'happens' to work and could get broken in the future, or is it perfectly valid code that should always work?
In short, is 'getPath' guaranteed to return the same latLng objects that were passed in, or can it pass back new ones with the same lat and the same lng but anything else that google doesn't care about might not still be there?
Thanks for any assistance
Click on the line, and it should alert "one two three".
<!DOCTYPE html>
<html>
<head>
<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 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.0, -1.5),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var polyline = new google.maps.Polyline({
map: map,
strokeColor: "blue",
strokeThicknedss: 2
});
polyline.setPath([
getLatLng(51.9, -1.4, "one"),
getLatLng(52.0, -1.5, "two"),
getLatLng(52.0, -1.6, "three")
]);
google.maps.event.addListener(polyline, "click", function() {
var path = this.getPath().getArray();
var datas = [];
for(var i = 0; i < path.length; i++) {
var ll = path[i];
datas.push(ll.data);
}
alert(datas.join("\n"));
});
}
function getLatLng(lat, lng, data) {
var ll = new google.maps.LatLng(lat, lng);
ll.data = data;
return ll;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>

Well according to the docs getPath() 'retrieves the first path'. And you've just set the path using setPath()... I'm not sure Google are going to mess with that data; your approach seems sound to me.

I found that the best way for storing polylines is to use Google's encoding function in the geometry library.
var polylineToStore = google.maps.geometry.encoding.encodePath(polyline.getPath());
This sets the polylineToStore variable to a string. When you want to reuse that encoded polyline you only need to decode it:
polyline.setPath(google.maps.geometry.encoding.decodePath(polylineToStore))
https://developers.google.com/maps/documentation/javascript/geometry#Encoding

Related

How to get layer ID from existing google map

I'm trying to toggle layers of an existing map created on maps.google.com with google V3 API.
To toggle (display / hide) the layer I'm using .setMap function with map/null as argument.
My problem is that I've not found a way to get the list of the existing layers. So I've hardcoded the values in mapLayerNames, but I would have prefer to get them from 'map' variable. Which API am I missing from the doc?
here comes my code: lid are the layer Ids I'm looking for in the url...
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>KML Layers</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var mapLayerNames = [
"http://www.google.com/maps/d/u/1/kml?mid=z_wfVyI764I4.kPvsE6js2GAg&lid=z_wfVyI764I4.kIQKW-gOFhmU",
"http://www.google.com/maps/d/u/1/kml?mid=z_wfVyI764I4.kPvsE6js2GAg&lid=z_wfVyI764I4.k2u4vYNOkUIA",
"http://www.google.com/maps/d/u/1/kml?mid=z_wfVyI764I4.kPvsE6js2GAg&lid=z_wfVyI764I4.kcPBYmgvyhbI"
];
var map;
var ctaLayer = [];
function initialize() {
var paris = new google.maps.LatLng(43.5742118,1.4538968);
var mapOptions = {
zoom: 11,
center: paris
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (var i=0; i<mapLayerNames.length; i++) {
ctaLayer = new google.maps.KmlLayer({
url: mapLayerNames[i]
});
ctaLayer.setMap(map);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

How do I change the position of a Google Maps marker?

I have the following code for a map that I'm working on and I'd like to see if I can put custom markers throughout. The problem is that I can't seem to get the first marker to change position no matter if I input latitude and longitude. Perhaps I'm entering the information incorrectly.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>UmApp</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=key"></script>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(41.160531, -73.256303);
var mapOptions = {
zoom: 16,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: 41.159317, -73.257443,
map: map,
title: 'Hello World!'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
try
var marker = new google.maps.Marker({
position: new google.maps.LatLng(41.159317, -73.257443);
map: map,
title: 'Hello World!'
});
I still cannot make comments, so I'll answer your comment question here:
As Kostrzak said, you would need to write
var marker = new google.maps.Marker({
position: new google.maps.LatLng(41.159317, -73.257443),
map: map,
title: 'Hello World!'
});
(Careful with the semicolon instead of the comma. Although it should work anyway, it may throw a bunch of errors on some IDEs).
The position inside the Marker object is expecting coordinates, but not in any form. It needs to have those coordinates given in a specific way: As a LatLng object. Because of this, you need to set those coordinates using the Google JavaScript library, which creates an object with your specified coordinates:
position: new google.maps.LatLng(41.159317, -73.257443)
Here you have SET the position of the marker. If you want to change it, you just need to set
marker.position = new google.maps.LatLng({newLat}, {newLng});
If you opened the console, you'd see a bunch of errors thrown by the position line: "Uncaught SyntaxError: Unexpected token - ". Console logs are pretty helpful most of the times, so use them!

How to link different URLs to multiple map markers for API v3

Checked these out here:
Google Maps API V3 multiple markers with links
Google Maps marker as a link
but they didn't help. I'm not programming savvy and total n00b. I'm simply trying to add some marker animations to my webpage. I'd like to be able to click on an individual marker once it settles and be redirected to that associated marker url.
Update: thank you so much for following up on this. However I get a blank screen when I try to run the html page. I updated my code below. I also removed the z index and put all your code updates between the tags inside the tag) Finally, I removed the intialize(); call function and instead used the . Running the code should theoretically drop 3 markers onto the map with the designated urls given the neighborhoods.length = 3. However the page still remains blank after refreshing.
So something is blocking the browser from loading the map onto the page. Does the map-canvas need to be adjusted in the ? My updated code is in next post below: –
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Marker animations with <code>setTimeout()</code></title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"
type="text/javascript"></script>
</head>
<body onload="initialize()";>
<script>
<div id="panel" style="margin-left: -52px">
<button id="drop" onclick="drop()">Drop Markers</button>
</div>
<div id="map-canvas"></div>
var sacramento = new google.maps.LatLng(38.576725, -121.493715);
var iterator = 0; // I added back this initialized variable which //wasn't in your adjusted code shown here
var neighborhoods = [
new google.maps.LatLng(38.576725, -121.493715),
new google.maps.LatLng(35.011263, -115.473376),
new google.maps.LatLng(33.941820, -118.408466)];
var markers = [];
var map;
var mapUrl = [
'http://www.google.com',
'http://www.youtube.com',
'http://maps.google.com'];
function initialize() {
{......etc. }
</script>
</body>
</html>
You have several issues in your code. Syntax, etc. I have removed a few things from your code to make it easier to understand (setTimeout, toggleBounce, etc.). And I added the call to drop() function in the initialize() function. I also replaced the window.location.href by a display of the URL in a DIV. Check the fiddle link at the bottom.
var sacramento = new google.maps.LatLng(38.576725, -121.493715);
var neighborhoods = [
new google.maps.LatLng(38.576725, -121.493715),
new google.maps.LatLng(35.011263, -115.473376),
new google.maps.LatLng(33.941820, -118.408466)];
var markers = [];
var map;
var mapUrl = [
'http://www.google.com',
'http://www.youtube.com',
'http://maps.google.com'];
function initialize() {
var mapOptions = {
zoom: 5,
center: sacramento
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
drop();
}
function drop() {
for (var i = 0; i < neighborhoods.length; i++) {
addMarker(i);
}
}
function addMarker(iterator) {
var marker = new google.maps.Marker({
position: neighborhoods[iterator],
map: map,
draggable: false,
url: mapUrl[iterator],
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', function () {
document.getElementById('goToLocation').innerHTML = 'Will send you to ' + this.url;
});
markers.push(marker);
}
initialize();
This should help you to get started.
JSFiddle

How to make the text fit a google marker?

I have written a code for displaying markers on the screen. And I have a text within the marker. The text is a 5 digit number which doesnot fit the marker. How can make the number to be within the marker?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Google Map API V3: Add Marker</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<style type="text/css">
body { margin: 20; padding: 20 }
#map_canvas{
width: 1024px;
height: 740px;
}
</style>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(47.576897,-122.419184),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var locations = [
[47.648197,-122.282784,11500,"0"]
];
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var shape = {
coord: [10, 10, 10, 20, 18, 20, 18 , 10],
type: 'poly'
};
for (i = 0; i < locations.length; i++) {
var myLatlng = new google.maps.LatLng(locations[i][0], locations[i][1]);
pinIcon = new google.maps.MarkerImage(
'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+locations[i][2]+'|808000|0000FF',
null,
null,
new google.maps.Point(140, 210),
new google.maps.Size(40, 60)
);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon:pinIcon,
shape:shape,
title: locations[i][3]
});
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
I want to print "11500" (locations[i][2]) inside my marker but when trying to do so it goes outside the marker.
The main issue is simply that you're using the wrong icon from the charts api. The pin type is of course not going to meet your needs for displaying the text; and you can't scale it after requesting it (as you seem to be trying in your code) since you'll be scaling the icon along with the text.
So two things to change:
MarkerIcon is deprecated, luckily it's easy to switch to Icon.
Use a different marker type that's designed for displaying text. Bubbles, probably.
Here is the relevant chunk of code that I just tested:
var myLatlng = new google.maps.LatLng(locations[i][0], locations[i][1]);
var pinIcon = {
url: 'http://chart.apis.google.com/chart?chst=d_bubble_text_small&chld=bb|'+locations[i][2]+'|C6EF8C|000000'
};
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: pinIcon,
title: locations[i][3]
});
I removed the shape attribute, because it's no longer valid with the new icon anyway. There is some image shifting during zoom, you can play with the attributes to fix that if you wish. And finally, there's different styles at that link to customize with.
Note: If this is to be used for a long time, know that the charts api is also deprecated, I think it's up until 2015.

Opening media from google maps custom marker

So I'm working on a custom google maps tour type application and I'm wondering how to get media to popup when I click a link within a google maps marker. Ideally this is what I would like to happen:
1. User clicks on marker and the normal white box comes up like on real Google Maps.
2. Within that text box I would like to have a button that will launch media that I have stored on a SQL server somewhere. This media could be audio, pictures, or video.
The code I have so far is below. If anyone could let me know how to do this, or point me in the right direction that would be awesome!
Thanks
<!doctype html>
<html>
<head>
<title>HuskyWalk Application Demo</title>
<meta name="viewport" conmtent="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #mapcanvas {
margin: 0;
padding: 0;
height: 98%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
var iteCoords = new google.maps.LatLng(41.806501, -72.252769);
//var mapCoords = new google.maps.LatLng(navigator.getCurrentPosition().coords.latitude, navigator.getCurrentPosition().coords.longitude);
//var mapCoords = new navigator.getCurrentPosition().coords;
function initialize() {
//var position = new navigator.geolocation.getCurrentLocation(showPosition);
var mapOptions = {
zoom: 18,
center: iteCoords,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById('mapcanvas'), mapOptions);
google.maps.event.addListenerOnce(map, "bounds_changed", watchStart);
var marker = createMarker(); //creates marker
}
function watchStart() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function createMarker() {
var marker = new google.maps.Marker({
position: iteCoords,
map: map,
title: 'ITEB',
});
google.maps.event.addListener(marker, "click", onMarker_clicked);
return marker;
}
function onMarker_clicked() {
alert(this.get('id'));
}
</script>
</head>
<body onload="initialize()">
<div id="mapcanvas"></div>
<div>
<p>Maps provided by Google Maps</p>
</div>
</body>
</html>
I know there is going to need to be some stuff in the onMarker_Clicked() method most likely, I'm just not sure what.
You'll want to use an InfoWindow and call its open() method from the click event handler.
See also the section in the google maps developer guide https://developers.google.com/maps/documentation/javascript/overlays#InfoWindows

Categories