Google Maps API custom marker not rendering - javascript

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"] });
});

Related

Trying to apply an event listener to the <li> values in view model, shows google is not defined

The code may seem idiotic. This is my first try at using knockout.
I am working on a neighborhood map. The task is to invoke an event when any item on the list is clicked. The event is, when the item(place title) is clicked, the respective marker shows a infoWindow. I tried to implement it and ended up using google API function. Its not happening. I need a way solve this and make it happen.
HTML
<div>
<h1>Famous places in Bhubaneswar</h1>
<section class="main">
<form class="search" method="post" action="index.html" >
<input type="text" data-bind="textInput: filter" placeholder="Click here/Type the name of the place">
<ul style="list-style-type: none;" data-bind="foreach: filteredItems">
<li>
<span data-bind="text: title, click: $parent.showInfoWindow"></span>
</li>
</ul>
</form>
</section>
<div id="map"></div>
</div>
JS
var map;
var locations = [
{
title: 'Lingaraj Temple',
location:
{
lat: 20.2382383,
lng: 85.8315622
}
},
{
title: 'Odisha State Museum',
location:
{
lat: 20.2562,
lng: 85.8415
}
},
{
title: 'Dhauli',
location:
{
lat: 20.1923517,
lng: 85.8372062
}
},
{
title: 'Nandankanan Zoological Park',
location:
{
lat: 20.395775,
lng: 85.8237923
}
},
{
title: 'Udayagiri Caves',
location:
{
lat: 20.2631,
lng: 85.7857
}
},
{
title: 'Kalinga Stadium',
location:
{
lat: 20.2879847,
lng: 85.8215891
}
}
];
var center =[{lat : 20.2961, lng : 85.8245}]
var markers = []; // Creating a new blank array for all the listing markers.
var styles = [
{
featureType: 'water',
stylers: [
{ color: '#19a0d8' }
]
},
{
featureType: 'administrative',
elementType: 'labels.text.stroke',
stylers: [
{ color: '#ffffff' },
{ weight: 6 }
]
},
{
featureType: 'administrative',
elementType: 'labels.text.fill',
stylers: [
{ color: '#e85113' }
]
},
{
featureType: 'road.highway',
elementType: 'geometry.stroke',
stylers: [
{ color: '#efe9e4' },
{ lightness: -40 }
]
},
{
featureType: 'transit.station',
stylers: [
{ weight: 9 },
{ hue: '#e85113' }
]
},
{
featureType: 'road.highway',
elementType: 'labels.icon',
stylers: [
{ visibility: 'off' }
]
},
{
featureType: 'water',
elementType: 'labels.text.stroke',
stylers: [
{ lightness: 100 }
]
},
{
featureType: 'water',
elementType: 'labels.text.fill',
stylers: [
{ lightness: -100 }
]
},
{
featureType: 'poi',
elementType: 'geometry',
stylers: [
{ visibility: 'on' },
{ color: '#f0e4d3' }
]
},
{
featureType: 'road.highway',
elementType: 'geometry.fill',
stylers: [
{ color: '#efe9e4' },
{ lightness: -25 }
]
}
];
function initMap() {
// Constructor creates a new map
map = new google.maps.Map(document.getElementById('map'), {
center: center[0],
zoom: 13,
styles: styles,
mapTypeControl: false
});
var largeInfowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var defaultIcon = makeMarkerIcon('0091ff'); // this is the default marker icon.
var highlightedIcon = makeMarkerIcon('FFFF24'); // this is the state of the marker when highlighted.
for (var i = 0; i < locations.length; i++) {
var position = locations[i].location; // Get the position from the location array.
var title = locations[i].title;
// var locationUrl = wikiLink(locations[i]);
// console.log(locationUrl);
wikiLink(locations[i]);
// Create a marker per location, and put into markers array.
var marker = new google.maps.Marker({
map: map,
position: position,
title: title,
animation: google.maps.Animation.DROP,
id: i,
// url: locationUrl
});
markers.push(marker); // Push the marker to our array of markers.
// Create an onclick event to open an infowindow at each marker.
marker.addListener('click', function() {
populateInfoWindow(this, largeInfowindow);
});
bounds.extend(markers[i].position);
marker.addListener('mouseover', function() {
this.setIcon(highlightedIcon);
});
marker.addListener('mouseout', function() {
this.setIcon(defaultIcon);
});
}
// Extend the boundaries of the map for each marker
map.fitBounds(bounds);
function wikiLink(location) {
location.url = '';
var wikiUrl = 'https://en.wikipedia.org/w/api.php?action=opensearch&search=' + title + '&format=json&callback=wikiCallback';
//If you cant get a wiki request, throw an error message.
var wikiError = setTimeout(function() {
location.url = 'Unable to find the request';
}, 8000);
$.ajax({
url: wikiUrl,
dataType: "jsonp",
jsonp: "callback",
success: function(response) {
console.log(response);
var url = response[3][0];
console.log(url);
location.url = url;
console.log(location.url);
clearTimeout(wikiError);
}
});
};
}
// This function populates the infowindow when the marker is clicked. We'll only allow
// one infowindow which will open at the marker that is clicked, and populate based
// on that markers position.
function populateInfoWindow(marker, infowindow) {
// Check to make sure the infowindow is not already opened on this marker.
if (infowindow.marker != marker) {
infowindow.setContent(''); // Clear the infowindow content to give the streetview time to load.
infowindow.marker = marker;
// Make sure the marker property is cleared if the infowindow is closed.
infowindow.addListener('closeclick', function() {
infowindow.marker = null;
});
var streetViewService = new google.maps.StreetViewService();
var radius = 500;
// In case the status is OK, which means the pano was found, compute the
// position of the streetview image, then calculate the heading, then get a
// panorama from that and set the options
function getStreetView(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var nearStreetViewLocation = data.location.latLng;
var heading = google.maps.geometry.spherical.computeHeading(
nearStreetViewLocation, marker.position);
console.log(marker.position);
infowindow.setContent('<div>' + marker.title + '</div><hr><div id="pano"></div><div><a href=' + location.url + '> Click here for more info </a></div>');
var panoramaOptions = {
position: nearStreetViewLocation,
pov: {
heading: heading,
pitch: 30
}
};
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('pano'), panoramaOptions);
} else {
infowindow.setContent('<div>' + marker.title + '</div><hr>' + '<div>No Street View Found</div>');
}
}
// Use streetview service to get the closest streetview image within 50 meters of the markers position
streetViewService.getPanoramaByLocation(marker.position, radius, getStreetView);
infowindow.open(map, marker); // Open the infowindow on the correct marker.
}
}
// This function takes in a COLOR, and then creates a new marker icon of that color.
// The icon will be 21 px wide by 34 high, have an origin of 0, 0 and be anchored at 10, 34).
function makeMarkerIcon(markerColor) {
var markerImage = new google.maps.MarkerImage(
'http://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|'+ markerColor +
'|40|_|%E2%80%A2',
new google.maps.Size(21, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34),
new google.maps.Size(21,34));
return markerImage;
}
function viewModel(markers) {
var self = this;
self.filter = ko.observable(''); // this is for the search box, takes value in it and searches for it in the array
self.items = ko.observableArray(locations); // we have made the array of locations into a ko.observableArray
// attributed to - http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html , filtering through array
self.filteredItems = ko.computed(function() {
var filter = self.filter().toLowerCase();
if (!filter) {
return self.items();
} else {
return ko.utils.arrayFilter(self.items(), function(id) {
console.log(id.title);
return stringStartsWith(id.title.toLowerCase(), filter);
});
}
});
var stringStartsWith = function (string, startsWith) {
string = string || "";
if (startsWith.length > string.length)
return false;
return string.substring(0, startsWith.length) === startsWith;
};
// populateInfoWindow(self.filteredItems,)
this.listInfoWindow = new google.maps.InfoWindow();
for (var i = 0; i < markers.length; i++) {
var marker = markers[i];
this.showInfoWindow = function(marker) {
marker.addListener('click', function() {
populateInfoWindow(this, largeInfowindow);
});
}
}
// this.showInfoWindow = function(place) { // this should show the infowindow if any place on the list is clicked
// console.log(place.marker);
// google.maps.event.trigger(place.marker, 'click');
// };
}
ko.applyBindings(new viewModel());
You haven't shown it here, but I expect that you're loading the Google Map API asyncronously, and then trying to use that API in your JS/Knockout code before it has finished loading. I did this project, and I had that problem for a bit.
What you need to do is delay your JS code from running until the Google Map API has fully loaded in. You can do that with a callback. You can see it used on this page from the API's docs.

Add addresses content to multiple google map markers

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/

Google Maps API V3: Exclude single marker from clustering

I am using the google maps api and using grid clustering for the markers. I wanted to know if there is a way to exclude a single marker from clustering. I want a "You are here" marker that is always visible. I tried using a different array for just that marker and not including it the cluster function but that didn't work.
Does anyone have a solution for this?
Here is how i am doing the clustering
$(document).on('click', '#mapbut', function() {
var items, distances, you_are_here = [], markers_data = [], markers_data2 = [], fred, clust1, markss;
you_are_here.push({
lat : Geo.lat,
lng : Geo .lng,
animation: google.maps.Animation.DROP,
title : 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
infoWindow: {
content: '<p>You are Here</p>'
}
});
function loadResults (data) {
if (data.map.length > 0) {
items = data.map;
for (var i = 0; i < items.length; i++)
{
var item = items[i];
var distances = [];
var dist2;
if (item.Lat != undefined && item.Lng != undefined)
{
markers_data.push({
lat : item.Lat,
lng : item.Lng,
title : item.Site,
infoWindow: {
content: '<p>' + item.Site + '</p><p>' + Math.round(item.distance) + ' miles away</p>'
}
});
}
}
}
map.addMarkers(markers_data);
map = new GMaps({
el: '#map',
lat: Geo.lat,
lng: Geo.lng,
zoom: 10,
mapTypeControl: false,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
markerClusterer: function(map) {
options = {
gridSize: 50
}
clust1 = new MarkerClusterer(map,[], options);
return clust1;
},
scaleControl: true,
streetViewControl: false
});
map.addMarkers(you_are_here);
The GMaps clusters all the markers you add to it with the addMarker method (if you provide a MarkerClusterer).
One option: add your "special" marker (the one that you don't want clustered) to the map manually, so it isn't added to the MarkerClusterer:
The GMaps.map property is a reference to the Google Maps Javascript API v3 map object. So this will add a marker to the map without letting the GMaps library know about it:
you_are_here = new google.maps.Marker({
position: {lat: Geo.lat,lng: Geo.lng},
animation: google.maps.Animation.DROP,
title: 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
map: map.map
});
proof of concept fiddle
code snippet:
var Geo = {
lat: 40.7281575,
lng: -74.07764
};
$(document).on('click', '#mapbut', function() {
var items, distances, you_are_here = [],
markers_data = [],
markers_data2 = [],
fred, clust1, markss;
function loadResults(data) {
if (data.map.length > 0) {
items = data.map;
for (var i = 0; i < items.length; i++) {
var item = items[i];
var distances = [];
var dist2;
if (item.Lat != undefined && item.Lng != undefined) {
markers_data.push({
lat: item.Lat,
lng: item.Lng,
title: item.Site,
infoWindow: {
content: '<p>' + item.Site + '</p><p>' + Math.round(item.distance) + ' miles away</p>'
}
});
}
}
}
map = new GMaps({
el: '#map',
lat: Geo.lat,
lng: Geo.lng,
zoom: 8,
mapTypeControl: false,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
markerClusterer: function(map) {
options = {
gridSize: 50,
imagePath: "https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m"
}
clust1 = new MarkerClusterer(map, [], options);
return clust1;
},
scaleControl: true,
streetViewControl: false
});
map.addMarkers(markers_data);
you_are_here = new google.maps.Marker({
position: {
lat: Geo.lat,
lng: Geo.lng
},
animation: google.maps.Animation.DROP,
title: 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
infoWindow: {
content: '<p>You are Here</p>'
},
map: map.map
});
// map.addMarkers(you_are_here);
}
loadResults(data);
});
var data = {
map: [{
Lat: 40.7127837,
Lng: -74.005941,
Site: "New York, NY",
distance: 1
}, {
Site: "Newark, NJ",
Lat: 40.735657,
Lng: -74.1723667,
distance: 2
}]
};
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://rawgit.com/HPNeo/gmaps/master/gmaps.js"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/src/markerclusterer.js"></script>
<input id="mapbut" type="button" value="map" />
<div id="map"></div>
To get around this is relatively simple, just after I send the markers array to MarkerClusterer I then add my location.
// Setup cluster markers
var markerCluster = new MarkerClusterer( gmap.map, options )
// add my location
gmap.addMarker({
lat: data.latitude,
lng: data.longitude
...
})
Thanks

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