Add addresses content to multiple google map markers - javascript

I want to add the location address to the marker content. I'm getting the address by the coordinates and this is working, but on the map will always display only the last address.
Here is my example code:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 400px;
}
#map_canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="map">
<div id="map_canvas" class="mapping"></div>
</div>
<script>
function initMap() {
var locations = [
[-33.890542, 151.274856],
[-33.923036, 151.259052],
];
var styleArray = [
{
featureType: 'all',
stylers: [
{saturation: -80}
]
}, {
featureType: 'road.arterial',
elementType: 'geometry',
stylers: [
{hue: '#00ffee'},
{saturation: 50}
]
}, {
featureType: 'poi.business',
elementType: 'labels',
stylers: [
{visibility: 'on'}
]
}
];
var image = {
url: 'map_icon.png',
size: new google.maps.Size(30, 45),
origin: new google.maps.Point(0, 0),
scaledSize: new google.maps.Size(25, 35),
};
var map = new google.maps.Map(document.getElementById('map'), {
scrollwheel: false,
zoom: 8,
center: new google.maps.LatLng(-33.92, 151.25), // default map position
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: styleArray,
});
var infowindow = new google.maps.InfoWindow();
var geocoder = new google.maps.Geocoder();
var marker, i;
var mapContent = '';
for (i = 0; i < locations.length; i++) {
var latLng = new google.maps.LatLng(locations[i][0], locations[i][1]);
geocoder.geocode({
latLng: new google.maps.LatLng(locations[i][0], locations[i][1]),
},
function (responses) {
if (responses && responses.length > 0) {
mapContent = responses[0].formatted_address;
}
}
);
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map,
icon: image,
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(mapContent);
infowindow.open(map, marker);
}
})(marker, i));
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap&sensor=true"></script>
</body>
</html>

Read some docs about Using closures in event listeners:
geocoder.geocode({
latLng: new google.maps.LatLng(locations[i][0], locations[i][1]),
},
function (responses) {
if (responses && responses.length > 0) {
mapContent = responses[0].formatted_address;
var marker = new google.maps.Marker({
position: responses[0].geometry.location,
map: map,
icon: image,
});
addContent(map, marker, mapContent, infowindow);
}
}
);
function addContent(map, marker, mapContent, infowindow ){
google.maps.event.addListener(marker, 'click', (function (marker) {
return function () {
infowindow.setContent(mapContent);
infowindow.open(map, marker);
}
})(marker));
}
JS fiddle: http://jsfiddle.net/4mtyu/2029/

Related

Google Maps API custom marker not rendering

So iam using google maps api to make my custom marker, data for multiple marker already created in my controller and exist when i check it via js console
<script>
var markersOnMap = {{ Js::from($marker) }};
</script>
[array collection checked][1]
[1]: https://i.stack.imgur.com/WO2Z5.png
and this is my maps.js class
var map;
var InforObj = [];
// Add a marker clusterer to manage the markers.
// center map
var centerCords = {
lat: -6.917076,
lng: 107.618979
};
window.onload = function() {
initMap();
};
// marker funtion
function addMarker() {
var markers = [];
for (var i = 0; i < markersOnMap.length; i++) {
var contentString = '<div id="content"> <p> <b>' + markersOnMap[i].placeName +
'</b> </p></div>' + '<a target="_blank" href="' + markersOnMap[i].url + '">Show Details</a>';
const marker = new google.maps.Marker({
position: markersOnMap[i].LatLng[0],
map: map
});
const infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 200
});
marker.addListener('click', function() {
closeOtherInfo();
infowindow.open(marker.get('map'), marker);
InforObj[0] = infowindow;
});
marker.addListener('mouseover', function() {
closeOtherInfo();
infowindow.open(marker.get('map'), marker);
InforObj[0] = infowindow;
});
}
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js'
});
}
function closeOtherInfo() {
if (InforObj.length > 0) {
/* detach the info-window from the marker ... undocumented in the API docs */
InforObj[0].set("marker", null);
/* and close it */
InforObj[0].close();
/* blank the array */
InforObj.length = 0;
}
}
// Add controls to the map, allowing users to hide/show features.
const styleControl = document.getElementById("style-selector-control");
const styles = {
default: [],
hide: [{
featureType: "poi",
stylers: [{ visibility: "off" }],
},
{
featureType: "transit",
elementType: "labels.icon",
stylers: [{ visibility: "off" }],
},
],
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: centerCords,
mapTypeControl: false,
});
// map.controls[google.maps.ControlPosition.TOP_LEFT].push(styleControl);
map.setOptions({ styles: styles["hide"] });
document.getElementById("hide-poi").addEventListener("click", () => {
map.setOptions({ styles: styles["hide"] });
});
document.getElementById("show-poi").addEventListener("click", () => {
map.setOptions({ styles: styles["default"] });
});
addMarker();
}
but when i check my maps on browser its empty, what should i do ?
fixed , i rewrite my maps.js became like this
var map = new google.maps.Map(document.getElementById('map2'), {
zoom: 13,
center: new google.maps.LatLng(-6.917076, 107.618979),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][2], locations[i][3]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('<p>' + locations[i][0] + '</p>' + locations[i][1] + '<br>' + '<a target="_blank" href="' + locations[i][4] + '">Show Details</a>');
infowindow.open(map, marker);
}
})(marker, i));
}
const styles = {
default: [],
hide: [{
featureType: "poi",
stylers: [{ visibility: "off" }],
},
{
featureType: "transit",
elementType: "labels.icon",
stylers: [{ visibility: "off" }],
},
],
};
map.setOptions({ styles: styles["hide"] });
document.getElementById("hide-poi").addEventListener("click", () => {
map.setOptions({ styles: styles["hide"] });
});
document.getElementById("show-poi").addEventListener("click", () => {
map.setOptions({ styles: styles["default"] });
});

Set marker in the callback function where user's position is available after creating the map

I made a function that display nearest hotels in google map.my code is as follow.
var map;
function initMap() {
var latlng = new google.maps.LatLng(28.535516,77.391026);
if (navigator.geolocation) {
try {
navigator.geolocation.getCurrentPosition(function(position) {
var myLocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
setPos(myLocation);
});
} catch (err) {
var myLocation = {
lat: 25.2048,
lng: 55.2708
};
setPos(myLocation);
}
} else {
var myLocation = {
lat: 25.2048,
lng: 55.2708
};
setPos(myLocation);
}
}
function setPos(myLocation) {
map = new google.maps.Map(document.getElementById('map'), {
center: myLocation,
zoom: 10
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: myLocation,
radius: 4000,
types: ['hotels']
}, processResults);
}
function processResults(results, status, pagination) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
} else {
createMarkers(results);
}
}
function createMarkers(places) {
var bounds = new google.maps.LatLngBounds();
var placesList = document.getElementById('places');
for (var i = 0, place; place = places[i]; i++)
{
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
animation: google.maps.Animation.DROP,
position: place.geometry.location
});
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
}
html,body {
margin: 0;
padding: 0;
}
#map {
height: 500px;
margin: 10px auto;
width: 800px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuBzeYkYimIquGG5KkIcB6vFmtHMUzDFo&libraries=places&callback=initMap" async defer></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuBzeYkYimIquGG5KkIcB6vFmtHMUzDFo&libraries=places"></script>
<div id="map"></div>
Above Example Returns me nearest hotels around user location. but i wants to also display users location pointer.
So how can i show users location here.
i also try by custom adding in initMap() function to show users location marker but it OVERRIDE with Hotels icons. so when i refresh page first for microseconds user location shows and than hotels icon will override that.
here is my image with o/p of above code.
Output of Fiddle Snippet
Add the creation of the marker to the setPos function (where the geolocation results are available and the map has been create.
proof of concept fiddle
when geolocation fails:
when geolocation works, it shows my current location.
code snippet:
var map;
function error() {
console.log("error!")
var myLocation = {
lat: 25.2048,
lng: 55.2708
};
setPos(myLocation);
}
function initMap() {
var latlng = new google.maps.LatLng(28.535516, 77.391026);
if (navigator.geolocation) {
try {
navigator.geolocation.getCurrentPosition(function(position) {
var myLocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
setPos(myLocation);
}, error);
} catch (err) {
var myLocation = {
lat: 25.2048,
lng: 55.2708
};
setPos(myLocation);
}
} else {
var myLocation = {
lat: 25.2048,
lng: 55.2708
};
setPos(myLocation);
}
}
function setPos(myLocation) {
map = new google.maps.Map(document.getElementById('map'), {
center: myLocation,
zoom: 10
});
var marker = new google.maps.Marker({
position: myLocation,
map: map,
title: "My Position"
})
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: myLocation,
radius: 4000,
types: ['hotels']
}, processResults);
}
function processResults(results, status, pagination) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
} else {
createMarkers(results);
}
}
function createMarkers(places) {
var bounds = new google.maps.LatLngBounds();
var placesList = document.getElementById('places');
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
animation: google.maps.Animation.DROP,
position: place.geometry.location
});
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
}
html,
body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
#map {
height: 100%;
margin: 10px auto;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap" async defer></script>
<div id="map"></div>

How to create a polyline between the source and destination using google maps api

I'm trying to show the path between the source and destination and also trying to move an icon in this given path.
I was able to move an icon from the source and destination but the path is getting revealed only when the icon is moving.
I want the whole path to be shown at the beginning itself.
<!DOCTYPE html>
<html>
<head>
<title>Animated route</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry"></script>
<script>
function initialize() {
var map = new google.maps.Map(document.getElementById("map"), {
center: {lat: 17.416483, lng: 78.513592},
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
getDirections(map);
}
function moveMarker(map, marker, latlng) {
marker.setPosition(latlng);
map.panTo(latlng);
}
function autoRefresh(map, pathCoords) {
var i, route, marker;
route = new google.maps.Polyline({
path: [],
geodesic : true,
strokeColor: 'blue',
strokeOpacity: 1.0,
strokeWeight: 2,
editable: false,
map:map
});
marker=new google.maps.Marker({map:map, icon:"truck.png"});
for (i = 0; i < pathCoords.length; i++) {
setTimeout(function(coords) {
route.getPath().push(coords);
moveMarker(map, marker, coords);
}, 2000 * i, pathCoords[i]);
}
}
function getDirections(map) {
var directionsService = new google.maps.DirectionsService();
var start = new google.maps.LatLng(17.416483, 78.513592);
var end = new google.maps.LatLng(17.424643, 78.645126);
var marker = new google.maps.Marker({
position: end,
map: map,
});
var marker = new google.maps.Marker({
position: start ,
map: map,
icon:"http://maps.google.com/mapfiles/ms/icons/green-dot.png"
});
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
autoRefresh(map, result.routes[0].overview_path);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
The simplest solution to display the complete route is to use the google.maps.DirectionRenderer, if you don't want it's markers, use the suppressMarkers: true option in its constructor, you can style the polyline as well.
// create the directionsDisplay reference
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true
});
// add it to the map
getDirections(map);
then use it to display the route:
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
autoRefresh(map, result.routes[0].overview_path);
}
});
code snippet:
<!DOCTYPE html>
<html>
<head>
<title>Animated route</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html,
body,
#map {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry"></script>
<script>
var directionsDisplay;
function initialize() {
var map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: 17.416483,
lng: 78.513592
},
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true
});
getDirections(map);
}
function moveMarker(map, marker, latlng) {
marker.setPosition(latlng);
map.panTo(latlng);
}
function autoRefresh(map, pathCoords) {
var i, route, marker;
route = new google.maps.Polyline({
path: [],
geodesic: true,
strokeColor: 'blue',
strokeOpacity: 1.0,
strokeWeight: 2,
editable: false,
map: map
});
marker = new google.maps.Marker({
map: map,
icon: pinSymbol("blue")
});
for (i = 0; i < pathCoords.length; i++) {
setTimeout(function(coords) {
route.getPath().push(coords);
moveMarker(map, marker, coords);
}, 2000 * i, pathCoords[i]);
}
}
function getDirections(map) {
var directionsService = new google.maps.DirectionsService();
var start = new google.maps.LatLng(17.416483, 78.513592);
var end = new google.maps.LatLng(17.424643, 78.645126);
var marker = new google.maps.Marker({
position: end,
map: map,
});
var marker = new google.maps.Marker({
position: start,
map: map,
icon: pinSymbol("red")
});
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
autoRefresh(map, result.routes[0].overview_path);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function pinSymbol(color) {
return {
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
fillColor: color,
fillOpacity: 1,
strokeColor: '#000',
strokeWeight: 2,
scale: 1
};
}
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

Addressing a google map to change setZoom by clicking on an external link

I've spent several hours trying to change the zoom level of a google map, using an onClick javascript function. I think my var map is inside the initialize function of the map, that's why it doesn't work, but I'm not sure. Thank you for your precious help.
Here we go:
1) My initialize function (with galeries corresponding to the data retrieved for the markers)
function initialize() {
var styles = [
{
stylers: [
{ hue: "#486FD5" },
{ saturation: 10 },
{ lightness: 20 },
{ gamma: 1.1 }
]
},{
featureType: "road",
elementType: "geometry",
stylers: [
{ lightness: 40 },
{ visibility: "simplified" }
]
},{
featureType: "road",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
];
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(46.8,1.7),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: false,
scrollwheel: false,
styles: styles
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
setMarkers(map, galeries);
}
function setMarkers(map, locations) {
var image = '/wordpress/wp-content/uploads/logo-25.png';
for (var i = 0; i < locations.length; i++) {
var galeries = locations[i];
var myLatLng = new google.maps.LatLng(galeries[1], galeries[2]);
var infoWindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
});
(function(i) {
google.maps.event.addListener(marker, "click", function() {
var galeries = locations[i];
infoWindow.close();
infoWindow.setContent(
"<div id='boxcontent'><a href='"+galeries[3]+"'><strong style='color:black'>"+ galeries[0] +"</strong></a><br />"+ galeries[4] +"</div>"
);
infoWindow.open(map, this);
});
})(i);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
2) My function called with onClick (all comments corresponding to KO solutions):
function zoom() {
//map_canvas.setCenter(marker.getPosition());
//map.setZoom(map.getZoom() + 1);
//map.setZoom('3');
//$('#map_canvas').gmap({'zoom':2});
//$('#map_canvas').setZoom(3);
//google.maps.map.setZoom(2);
//var carte = google.maps.Map(document.getElementById('map-canvas'));
//carte.setZoom(2);
//this.map.setZoom(2);
}
3) Result : nothing happens, and on the console I get :
Uncaught TypeError: Cannot read property 'setZoom' of undefined
If you make your map variable global, you can access it in HTML click event handlers.
function zoom() {
map.setZoom(map.getZoom() + 1);
}
var map; // make global map variable
function initialize() {
...
// initialize the global variable, remove the "var" keyword here
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
setMarkers(map, galeries);
}
working fiddle
working code snippet:
function zoom() {
map.setZoom(map.getZoom() + 1);
}
var map;
function initialize() {
var styles = [{
stylers: [{
hue: "#486FD5"
}, {
saturation: 10
}, {
lightness: 20
}, {
gamma: 1.1
}]
}, {
featureType: "road",
elementType: "geometry",
stylers: [{
lightness: 40
}, {
visibility: "simplified"
}]
}, {
featureType: "road",
elementType: "labels",
stylers: [{
visibility: "off"
}]
}];
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(46.8, 1.7),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: false,
scrollwheel: false,
styles: styles
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var galeries = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
setMarkers(map, galeries);
}
function setMarkers(map, locations) {
var bounds = new google.maps.LatLngBounds();
var image = 'http://maps.google.com/mapfiles/ms/icons/blue.png';
for (var i = 0; i < locations.length; i++) {
var galeries = locations[i];
var myLatLng = new google.maps.LatLng(galeries[1], galeries[2]);
bounds.extend(myLatLng);
var infoWindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
});
(function (i) {
google.maps.event.addListener(marker, "click", function () {
var galeries = locations[i];
infoWindow.close();
infoWindow.setContent(
"<div id='boxcontent'><a href='" + galeries[3] + "'><strong style='color:black'>" + galeries[0] + "</strong></a><br />" + galeries[4] + "</div>");
infoWindow.open(map, this);
});
})(i);
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map_canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
<input type="button" value="zoom" onclick="zoom()" />

street view and googlemaps

Im trying to solve a problem. I have a map locating parking and would like to put the street view. I got a place, but the array of "locations" does not work completely. The map shows only the last array in the street view (ps: you must click the icon to display the street view)
http://www.clicrbs.com.br/sites/swf/paulMapa/mapspaul.html
function initialize() {
var pinkParksStyles = [
{
featureType: "all",
stylers: [
{ saturation: -80 }
]
},
{
featureType: "poi.park",
stylers: [
{ hue: "#ff0023" },
{ saturation: 40 }
]
}
];
var pinkMapType = new google.maps.StyledMapType(pinkParksStyles,
{name: "Paul em Floripa"});
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(-27.619279,-48.527896),
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP,'pink_parks','satellite' ],
streetViewControl: true
}
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker();
var infowindow = new google.maps.InfoWindow();
var kmlLayer = new google.maps.KmlLayer('http://www.clicrbs.com.br/sites/swf/paulMapa/trajetoComum.kml');
var locations = [
['Estacionamento 1', -27.626216,-48.526806, 1],
['Estacionamento 2', -27.622654,-48.528102, 2],
['Estacionamento 3', -27.618236,-48.528598, 3],
['Estacionamento 4', -27.615011,-48.529491, 4],
['Estacionamento 5', -27.613015,-48.532554, 5],
['Estacionamento 6', -27.612033,-48.534453, 6],
['Estacionamento 7', -27.611326,-48.530995, 7],
['Estacionamento 8', -27.613811,-48.527514, 8],
];
var pano = null;
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
icon: 'images/stopcar.png',
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i ) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i))
google.maps.event.addListener(infowindow, 'domready', function() {
if (pano != null) {
pano.unbind("position");
pano.setVisible(false);
}
pano = new google.maps.StreetViewPanorama(document.getElementById("content"), {
navigationControl: true,
enableCloseButton: true,
addressControl: true,
linksControl: false,
});
pano.bindTo("position", marker);
pano.setVisible(true);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
pano.unbind("position");
pano.setVisible(true);
pano = null;
});
}
kmlLayer.setMap(map);
map.mapTypes.set('pink_parks', pinkMapType);
map.setMapTypeId('pink_parks');
map.setStreetView(pano);
}
​
I decided
function initialize() {
var pinkParksStyles = [
{
featureType: "all",
stylers: [
{ saturation: -80 }
]
},
{
featureType: "poi.park",
stylers: [
{ hue: "#ff0023" },
{ saturation: 40 }
]
}
];
// Create the map
// No need to specify zoom and center as we fit the map further down.
var pinkMapType = new google.maps.StyledMapType(pinkParksStyles,
{name: "Paul em Floripa"});
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(-27.619279,-48.527896),
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP,'pink_parks','satellite' ],
streetViewControl: true
}
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var kmlLayer = new google.maps.KmlLayer('http://www.clicrbs.com.br/sites/swf/paulMapa/trajetoComum.kml');
// Define the list of markers.
// This could be generated server-side with a script creating the array.
var markers = [
{ lat:-27.626216, lng:-48.526806, name:"Estacionamento 1"},
{ lat:-27.622654, lng:-48.528102, name:"Estacionamento 2"},
{ lat:-27.618236, lng:-48.528598, name:"Estacionamento 3"},
{ lat:-27.615011, lng:-48.529491, name:"Estacionamento 4"},
{ lat:-27.613015, lng:-48.532554, name:"Estacionamento 5"},
{ lat:-27.612033, lng:-48.534453, name:"Estacionamento 6"},
{ lat:-27.611326, lng:-48.530995, name:"Estacionamento 7"},
{ lat:-27.613811, lng:-48.527514, name:"Estacionamento 8"},
];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
icon: 'images/stopcar.png',
map: map,
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.name;
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "400px";
streetview.style.height = "400px";
content.appendChild(streetview);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
google.maps.event.addListenerOnce(infowindow, "domready", function() {
var panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: true,
enableCloseButton: true,
addressControl: true,
linksControl: false,
visible: true,
position: marker.getPosition()
});
});
}
// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
var data = markers[index];
bounds.extend(new google.maps.LatLng(data.lat, data.lng));
}
map.fitBounds(bounds);
map.mapTypes.set('pink_parks', pinkMapType);
map.setMapTypeId('pink_parks');
kmlLayer.setMap(map);
}

Categories

Resources