Add KML file to map already created api v3 - javascript

I tried to add a KML file polygons to a map already created with their respective markers, with no apparent result.
It's possible?
For me it only works one way or the other.
URL KML file is located at the end of post.
var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
content: ''
});
// Our markers
markers1 = [
['0', 'CLI23456', -18.498682, -70.294426, 'as'],
['1', 'CLI12345', -18.499508, -70.295250, 'ap'],
['2', 'CLI78912', -18.497622, -70.293671, 'as'],
['3', 'CLI54321', -18.472946, -70.295662, 'pvp']
];
/**
* Function to init map
*/
function initialize() {
var center = new google.maps.LatLng(-18.476202, -70.307236);
var mapOptions = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (i = 0; i < markers1.length; i++) {
addMarker(markers1[i]);
}
}
/**
* Function to add marker to map
*/
function addMarker(marker) {
var category = marker[4];
var title = marker[1];
var pos = new google.maps.LatLng(marker[2], marker[3]);
var content = marker[1];
marker1 = new google.maps.Marker({
title: title,
position: pos,
category: category,
map: map
});
gmarkers1.push(marker1);
// Marker click listener
google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
return function () {
console.log('Gmarker 1 gets pushed');
infowindow.setContent(content);
infowindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(13);
}
})(marker1, content));
}
/**
* Function to filter markers by category
*/
filterMarkers = function (category) {
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}
}
// Init map
initialize();
#map-canvas {
width: 500px;
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map-canvas"></div>
<select id="type" onchange="filterMarkers(this.value);">
<option value="">Seleccionar categoría</option>
<option value="as">AS</option>
<option value="ap">AP</option>
<option value="pvp">PVP</option>
</select>
KML file polygons: My KML file polygons

You should use a kmlLayer
var map;
function initialize() {
var center = new google.maps.LatLng(-18.476202, -70.307236);
var mapOptions = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (i = 0; i < markers1.length; i++) {
addMarker(markers1[i]);
}
var mykmlLayer = new google.maps.KmlLayer({
url: 'http://redeslibres.cl/documentos/kml/SECTOR_AS.kml',
map: map
});
}

The native Google Maps Javascript KML renderer is KmlLayer.
var kmlLayer = new google.maps.KmlLayer({
url: 'http://redeslibres.cl/documentos/kml/SECTOR_AS.kml',
map: map
});
To prevent that from "auto-zooming" to fit the KML, use the preserveViewport: true option.
var kmlLayer = new google.maps.KmlLayer({
url: 'http://redeslibres.cl/documentos/kml/SECTOR_AS.kml',
map: map,
preserveViewport: true // prevent zoom from changing to fit KML
});
code snippet:
var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
content: ''
});
// Our markers
markers1 = [
['0', 'CLI23456', -18.498682, -70.294426, 'as'],
['1', 'CLI12345', -18.499508, -70.295250, 'ap'],
['2', 'CLI78912', -18.497622, -70.293671, 'as'],
['3', 'CLI54321', -18.472946, -70.295662, 'pvp']
];
/**
* Function to init map
*/
function initialize() {
var center = new google.maps.LatLng(-18.476202, -70.307236);
var mapOptions = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var kmlLayer = new google.maps.KmlLayer({
url: 'http://redeslibres.cl/documentos/kml/SECTOR_AS.kml',
map: map,
preserveViewport: true // prevent zoom from changing to fit KML
});
for (i = 0; i < markers1.length; i++) {
addMarker(markers1[i]);
}
}
/**
* Function to add marker to map
*/
function addMarker(marker) {
var category = marker[4];
var title = marker[1];
var pos = new google.maps.LatLng(marker[2], marker[3]);
var content = marker[1];
var marker1 = new google.maps.Marker({
title: title,
position: pos,
category: category,
map: map
});
gmarkers1.push(marker1);
// Marker click listener
google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
return function() {
console.log('Gmarker 1 gets pushed');
infowindow.setContent(content);
infowindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(13);
}
})(marker1, content));
}
/**
* Function to filter markers by category
*/
filterMarkers = function(category) {
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}
}
// Init map
initialize();
#map-canvas {
width: 500px;
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map-canvas"></div>
<select id="type" onchange="filterMarkers(this.value);">
<option value="">Seleccionar categoría</option>
<option value="as">AS</option>
<option value="ap">AP</option>
<option value="pvp">PVP</option>
</select>

Related

Google Map make a polyline connecting the markersMarker and Marker

I am a student trying to become a java developer in Korea
I want to draw a polyline connecting the markers with a click event, not with directions.
I'll give you an exampleenter image description here
It's not finished yet, but I'll show you what I made
I made a mistake but please understand
What I want is to draw a polyline by connecting two fixed markers.
var map, polyline,markers = new Array();
var stockholm = {lat:45,lng:10}; // 맵 중앙 설정
function initMap(){
// map options
var options = {
zoom:4,
center:stockholm,
streetViewControl: true,
draggable:true,
mapTypeId: "roadmap",
// 맵 기본 컨트롤 설정
mapTypeControl: true,
mapTypeControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_TOP
},
scaleControl: true
}
// Map 호출 ======================================================================
map = new google.maps.Map(document.getElementById('map'),options);
// polyline 옵션 지정 ============================================================
polyline = new google.maps.Polyline({
strokeColor: 'red',
strokeWeight: 3,
map: map
});
google.maps.event.addListener(map, 'click', function (event) {
addPoint(event.latLng);
});
// searchbox===================
const input = document.getElementById("pac-input");
const searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
let markers1 = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener("places_changed", () => {
const places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers1.forEach((marker) => {
marker.setMap(null);
});
markers1 = [];
// For each place, get the icon, name and location.
const bounds = new google.maps.LatLngBounds();
places.forEach((place) => {
if (!place.geometry || !place.geometry.location) {
console.log("Returned place contains no geometry");
return;
}
const icon = {
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),
};
// Create a marker for each place.
markers1.push(new google.maps.Marker({
map,
icon,
title: place.name,
position: place.geometry.location,
}));
if (place.geometry.viewport) {
bounds.union(place.geometry.viewport);
}else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
// 고정 마커 추가
var markers = [
// 가나
{
coords:{lat:6.6666004, lng:-1.6162709},
iconImage:'assets/img/places/stparkdublin.png',
content:'<div style="height:auto;width:400px;"><h1>가나-쿠마시</h1>쿠마시는 가나 아샨티 주의 주도이며 구 아샨티 왕국의 수도였다. 수도인 아크라에서 북서쪽으로 약 250km 떨어져 있다. 쿠마시는 적도로부터 북쪽으로 약 482km, 기니만으로터 북쪽으로 약 160km 에 위치한다.',
},
{
coords:{lat:5.6037168,lng:-0.1869644},
iconImage:'assets/img/places/botanic garden.png',
content:'<div style="height:auto;width:400px;"><h1>가나-아크라</h1>아크라는 가나 공화국의 수도이자 약 227만 명의 인구를 가진 가나 최대의 도시이다. 도시 자체도 아크라 메트로폴리스 특구에 속해 있으며, 그 면적은 약 139km²이다. 아크라의 관광지 중에 가나 국립 박물관이 있다. 코토카 국제공항이 있다.',
},
{
coords:{lat:5.1315, lng:-1.2794744},
iconImage:'assets/img/places/stparkdublin.png',
content:'<div style="height:auto;width:400px;"><h1>가나-케이프코스트</h1>케이프코스트는 가나의 항구 도시로, 중앙 주의 주도이다. 16세기부터 영국과 포르투갈, 스웨덴, 덴마크, 네덜란드의 통치를 받았다. 15세기 포르투갈이 이 곳을 발견했으며 1653년 스웨덴이 케이프코스트 성을 건설했다. 이 성은 현재 세계유산으로 지정되어 있다.',
},
{
coords:{lat:9.393908, lng:-0.8556313999999999},
iconImage:'assets/img/places/swordscastle.png',
content:'<div style="height:auto;width:400px;"><h1>가나-타말레</h1>타말레은 가나 북부 주의 주도이다. 인구는 55만명이다.',
},
{
coords:{lat:10.7875419, lng:-0.8579818},
iconImage:'assets/img/places/Howth.png',
content:'<div style="height:auto;width:400px;"><h1>가나-볼가탕가</h1>볼가탕가는 가나의 도시이다. 경작과 가축 사육이 주된 생업이다.',
},
];
var gmarkers = [];
for(var i = 0; i < markers.length; i++){
gmarkers.push(addMarker(markers[i]));
}
const sidebar = document.getElementById("sidebar"); // sidebar
var activeInfoWindow = null;
//Add MArker function
function addMarker(props){
var marker = new google.maps.Marker({
position:props.coords,
map:map,
descrip:props.content,
});
//Check content
if(props.content){
var infoWindow = new google.maps.InfoWindow({
content:props.content
});
marker.addListener('click',function(){
infoWindow.open(map,marker);
for(var i=0;i<markers.length;i++){
sidebar.innerHTML = props.content;
}
});
marker.addListener('click', function () {
if (activeInfoWindow) { activeInfoWindow.close();}
infoWindow.open(map, marker);
activeInfoWindow = infoWindow;
});
}
return marker;
}
var markerCluster = new MarkerClusterer(map, gmarkers,
{
imagePath:'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
gridSize:100,
minClusterSize:10,
});
}
google.maps.event.addDomListener(window, 'load', initMap);
//poly line ======================================================================
var latlnglatlng = new Array;
function removePoint(marker) {
for (var i = 0; i < markers.length; i++) {
if (markers[i] === marker) {
markers[i].setMap(null);
markers.splice(i, 1);
polyline.getPath().removeAt(i);
}
}
}
function addPoint(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
markers.push(marker);
//console.log(markers.position.lng.Scopes);
polyline.getPath().setAt(markers.length - 1, latlng);
google.maps.event.addListener(marker, 'click', function (event) {
removePoint(marker);
});
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDjtW34Ax16khc7UYth6--V4pNFX1XlHUE&libraries=places"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
Thanks again for watching I really want to solve this, I've been thinking about it for a month

Cannot remove markers from google maps api

The markers in my program just wont remove with the deleteMarkers() function
CSS:
#map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
HTML:
<div style="height:500px; width:750px;">
<div id="map-canvas"></div>
</div>
<select class="form-control" name="dateSelect" id="dateSelect" onchange="dateSelect_Event();"></select>
Javascript:
var map; <--- global variables
var locations = [];
var lat_get = '';
var long_get = '';
var marker=[];
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {lat: 7.072617, lng: 125.599494},
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 13,
});
};
function deleteMarkers() {
for (var i = 0; i < marker.length; i++ ) {
marker[i].setMap(null);
}
marker.length = 0;
}
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.setMap(map);
});
}
Firebase:
-databaseName
--location
---latitude
---longitude
I just use firebase to get the lat and long on every change of the html select option and it work perfectly. The problem this time is it can't delete the markers. Should I do the deleteMarkers differently?
Thanks to #StackSlave's answer. I was able to successfully remove it by creating and pushing the google_marker to the global marker variable.
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
var google_marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
google_marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.push(google_marker);
});
marker.setMap(map);
}

Show nearest elements on google map

I am creating a project using google map. My project contains hospital address ( in longitude and latitude) to be stored in database. But I want to show nearest hospital from my current location. And I am unable to figure out how to do it. Please help me with best algorithm and with some code.
Following code is used just to display all hospital address in map now I want is how to show only 3 nearest hospital from my current positiom.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
for (var i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var image = "img/iconHospital.png";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
title: data.district,
animation: animationType
});
}
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
See this example at. I adapted your code accordingly.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: nepalLocation,
radius: 50000,
type: ['hospital']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
if (i == 2) {
break;
}
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>

Adding actionListeners to dynamically created google markers to plot routes

I have a page that retrieves some locations from a database and creates markers based on their lat/long to display on a map. The markers are saved in an array and I use a for loop to assign onclick action listeners to each marker. When the user clicks on a marker I want a route from their current location to the marker location to be displayed. The issue I am having is that regardless of which marker is clicked, it always plots a route to the final marker in the array.
This is what the map looks like
In the above example I am going to click the red marker A.
As you can see it has plotted a course to marker D.
My Code:
//THIS FUNCTIONS BUILD THE MAPS
function initializeMap(position)
{ //USER LOCATION
var myCenter = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapProp =
{
center: myCenter,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapObj = new google.maps.Map(document.getElementById("googleMap"), mapProp);
//MAKING SURE THE DATA ARRAY HAS SOMETHING IN IT
if (ajaxResult.length > 0)
{
for (var i = 0; i < ajaxResult.length; i++)
{
var pos = {lat: parseFloat(ajaxResult[i][6]), lng: parseFloat(ajaxResult[i][7])};
//BUILDING THE DESTINATION MARKERS
var suggestionMarker = new google.maps.Marker({
position: pos,
icon: markerNames[i]
});
markers.push(suggestionMarker);//ADDING TO THE MARKER ARRAY
suggestionMarker.setMap(mapObj);//ADING TO THE MAP
var userString = ajaxResult[i][1];//INFORMATINO WINDOW
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, suggestionMarker);
}
addMarkerListeners(myCenter);
}
//MARKER FOR THE USER LOCATION
var userImage = 'assets/img/GoogleMapsMarkers/blue_MarkerA.png'
var userMarker = new google.maps.Marker({
position: myCenter,
icon: userImage
});
markers.push(userMarker);
userMarker.setMap(mapObj);
//USER INFORMATION WINDOW
var userString = "You!";
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, userMarker);
}
/*
*
* #param {type} option
* #returns {Boolean}
* ACCEPTS THE USER LOCATION AND ADDS ACTION LISTENERS TO EACH MARKER
* IN THE MARKER ARRAY. THE ACTION LISTENER CALLS THE PLOT ROUTE
* FUNCTION AND PASSES IT THE MARKER POSITION AND USER POSITION
*/
function addMarkerListeners(myCenter)
{
if(markers.length > 0)
{
for(var i = 0; i < markers.length-1; i++)
{
google.maps.event.addListener(markers[i],'click', function(){plotRoute(markers[i].getPosition(),myCenter);});
//markers[i].addEventListener('click', function(){plotRoute(markers[i].getPosition(),myCenter);});
directionsDisplay.setMap(mapObj);
}
}
}
//CREATES A ROUT
function plotRoute(pos, myCenter)
{
var request = {
origin: myCenter,
destination: pos,
travelMode: 'DRIVING'
};
directionsService.route(request, function(result,status){
if(status === 'OK')
{
directionsDisplay.setDirections(result);
}
});
}
Note that the actual final marker is always the user marker but the for loop is instructed not to include it. Can anyone see why it only ever plots a route to the final destination marker in the marker array?
This is a common problem with loops setting up event listeners. It is solved in this related question: Google Maps JS API v3 - Simple Multiple Marker Example using function closure. To use that solution in your code:
function addMarkerListeners(myCenter) {
if (markers.length > 0) {
for (var i = 0; i < markers.length; i++) {
// function closure on the "i" variable
google.maps.event.addListener(markers[i], 'click', (function(i) {
return function() {
plotRoute(markers[i].getPosition(), myCenter);
}})(i));
directionsDisplay.setMap(mapObj);
}
}
}
proof of concept fiddle
To solve it without function closure, you could use the this inside the event handler function, which refers to the marker clicked:
function addMarkerListeners(myCenter) {
if (markers.length > 0) {
for (var i = 0; i < markers.length; i++) {
google.maps.event.addListener(markers[i], 'click', function() {
plotRoute(this.getPosition(), myCenter);
});
directionsDisplay.setMap(mapObj);
}
}
}
proof of concept fiddle
code snippet (using function closure):
var geocoder;
var map;
var markers = [];
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
function initialize() {
// Googleplex 37.4223434, -122.0843689
var position = {coords: {latitude:37.4223434, longitude:-122.0843689}}
initializeMap(position);
}
google.maps.event.addDomListener(window, "load", initialize);
// Menlo Park, CA, USA (37.4529598, -122.18172520000002)
// Mountain View, CA, USA (37.3860517, -122.0838511)
var ajaxResult = [[0,"infowindow 0",2,3,4,5,37.4419,-122.1419],
[1,"infowindow 1",2,3,4,5,37.4529598,-122.1817252],[2,"infowindow 2",2,3,4,5,37.3860517,-122.0838511]]
//THIS FUNCTIONS BUILD THE MAPS
function initializeMap(position) { //USER LOCATION
var myCenter = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapProp = {
center: myCenter,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapObj = new google.maps.Map(document.getElementById("googleMap"), mapProp);
//MAKING SURE THE DATA ARRAY HAS SOMETHING IN IT
if (ajaxResult.length > 0) {
for (var i = 0; i < ajaxResult.length; i++) {
var pos = {
lat: parseFloat(ajaxResult[i][6]),
lng: parseFloat(ajaxResult[i][7])
};
//BUILDING THE DESTINATION MARKERS
var suggestionMarker = new google.maps.Marker({
position: pos,
// icon: markerNames[i]
});
markers.push(suggestionMarker); //ADDING TO THE MARKER ARRAY
suggestionMarker.setMap(mapObj); //ADING TO THE MAP
var userString = ajaxResult[i][1]; //INFORMATINO WINDOW
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, suggestionMarker);
}
addMarkerListeners(myCenter);
}
//MARKER FOR THE USER LOCATION
var userImage = 'http://maps.google.com/mapfiles/ms/micons/blue.png'
var userMarker = new google.maps.Marker({
position: myCenter,
icon: userImage
});
markers.push(userMarker);
userMarker.setMap(mapObj);
//USER INFORMATION WINDOW
var userString = "You!";
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, userMarker);
}
/*
*
* #param {type} option
* #returns {Boolean}
* ACCEPTS THE USER LOCATION AND ADDS ACTION LISTENERS TO EACH MARKER
* IN THE MARKER ARRAY. THE ACTION LISTENER CALLS THE PLOT ROUTE
* FUNCTION AND PASSES IT THE MARKER POSITION AND USER POSITION
*/
function addMarkerListeners(myCenter) {
if (markers.length > 0) {
for (var i = 0; i < markers.length; i++) {
google.maps.event.addListener(markers[i], 'click', (function(i) {
return function() {
plotRoute(markers[i].getPosition(), myCenter);
}})(i));
directionsDisplay.setMap(mapObj);
}
}
}
//CREATES A ROUTE
function plotRoute(pos, myCenter) {
var request = {
origin: myCenter,
destination: pos,
travelMode: 'DRIVING'
};
directionsService.route(request, function(result, status) {
if (status === 'OK') {
directionsDisplay.setDirections(result);
} else alert("directions request failed: "+status);
});
}
html,
body,
#googleMap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googleMap"></div>
code snippet (using this):
var geocoder;
var map;
var markers = [];
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
function initialize() {
// Googleplex 37.4223434, -122.0843689
var position = {coords: {latitude:37.4223434, longitude:-122.0843689}}
initializeMap(position);
}
google.maps.event.addDomListener(window, "load", initialize);
// Menlo Park, CA, USA (37.4529598, -122.18172520000002)
// Mountain View, CA, USA (37.3860517, -122.0838511)
var ajaxResult = [[0,"infowindow 0",2,3,4,5,37.4419,-122.1419],
[1,"infowindow 1",2,3,4,5,37.4529598,-122.1817252],[2,"infowindow 2",2,3,4,5,37.3860517,-122.0838511]]
//THIS FUNCTIONS BUILD THE MAPS
function initializeMap(position) { //USER LOCATION
var myCenter = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapProp = {
center: myCenter,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapObj = new google.maps.Map(document.getElementById("googleMap"), mapProp);
//MAKING SURE THE DATA ARRAY HAS SOMETHING IN IT
if (ajaxResult.length > 0) {
for (var i = 0; i < ajaxResult.length; i++) {
var pos = {
lat: parseFloat(ajaxResult[i][6]),
lng: parseFloat(ajaxResult[i][7])
};
//BUILDING THE DESTINATION MARKERS
var suggestionMarker = new google.maps.Marker({
position: pos,
// icon: markerNames[i]
});
markers.push(suggestionMarker); //ADDING TO THE MARKER ARRAY
suggestionMarker.setMap(mapObj); //ADING TO THE MAP
var userString = ajaxResult[i][1]; //INFORMATINO WINDOW
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, suggestionMarker);
}
addMarkerListeners(myCenter);
}
//MARKER FOR THE USER LOCATION
var userImage = 'http://maps.google.com/mapfiles/ms/micons/blue.png'
var userMarker = new google.maps.Marker({
position: myCenter,
icon: userImage
});
markers.push(userMarker);
userMarker.setMap(mapObj);
//USER INFORMATION WINDOW
var userString = "You!";
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, userMarker);
}
/*
*
* #param {type} option
* #returns {Boolean}
* ACCEPTS THE USER LOCATION AND ADDS ACTION LISTENERS TO EACH MARKER
* IN THE MARKER ARRAY. THE ACTION LISTENER CALLS THE PLOT ROUTE
* FUNCTION AND PASSES IT THE MARKER POSITION AND USER POSITION
*/
function addMarkerListeners(myCenter) {
if (markers.length > 0) {
for (var i = 0; i < markers.length; i++) {
google.maps.event.addListener(markers[i], 'click', function() {
plotRoute(this.getPosition(), myCenter);
});
directionsDisplay.setMap(mapObj);
}
}
}
//CREATES A ROUT
function plotRoute(pos, myCenter) {
var request = {
origin: myCenter,
destination: pos,
travelMode: 'DRIVING'
};
directionsService.route(request, function(result, status) {
if (status === 'OK') {
directionsDisplay.setDirections(result);
}
});
}
html,
body,
#googleMap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googleMap"></div>

Multiple "InfoWindow" for array of "markers" on Google Maps?

Using Google Maps API to add an infoWindow to each marker. Markers come from an array.
Although, infoWindow only shows up for the first marker, not the others. Why? Thanks.
function set_markers(array) {
var mapOptions = {
zoom: 13
}
for (var i = 0; i < array.length; i++) {
var single_location = array[i];
var myLatLng = new google.maps.LatLng(single_location[1], single_location[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: single_location[0]
});
var infowindow = new google.maps.InfoWindow({
content: ""
});
}
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<h3>'+this.title+'</h3>');
infowindow.open(map,this);
});
}
var infowindow = new google.maps.InfoWindow();
function set_markers(array) {
var mapOptions = {
zoom: 13
};
for (var i = 0; i < array.length; i++) {
var single_location = array[i];
var myLatLng = new google.maps.LatLng(single_location[1], single_location[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: single_location[0]
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent('<h3>' + this.title + '</h3>');
infowindow.open(map, this);
});
}
}
This is untested since you didn't post a MCVE.

Categories

Resources