我有一个像deviceId = [005305230001JIZZZZ, 085835360001NBGJZZ, 085835360002NBGJZZ]
这样的数组。
信息窗口应显示deviceId,并根据点击的标记显示。我几天前才开始关注JavaScript,无法理解这些功能如何工作,现在没有时间学习,因为我必须完成这项工作。我在这看到了一些实现,但我认为他们已经使用函数以不同的方式添加了多个标记。我无法理解,所以我使用for
循环。
latArray
和lngArray
有类似[12.1456,12.5256,11.566]
和[72.145,72.4557,75.23535]
我无法弄清楚如何为相应的标记添加信息窗口。
这是地图的代码:
function initMap() {
var bounds = new google.maps.LatLngBounds();
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv);
map.setCenter(new google.maps.LatLng(latArray[0],lngArray[0]));
map.setZoom(18);
for(i=0;i<latArray.length;i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(latArray[i],lngArray[i]),
map: map,
title:"This is the place.",
// icon:"phone4.png"
});
//bounds.extend(marker.getPosition());
console.log(latArray);
console.log(lngArray);
}
//map.fitBounds(bounds);
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
}
如何显示相应标记的信息窗口。
这是标记的内容:
contentString = '<div id = "content>'
+'<p style = "color:#000000">DeviceID<p>' +
'<p>'+ deviceId[i] + '<br></p>' //deviceId is the array with content
+ '</div>'
我读了一些关于闭包的内容,但不明白。请帮忙
编辑:我刚试过这个。我得到了js?callback=initMap:34 InvalidValueError: setPosition: not a LatLng or LatLngLiteral: not an Object
我尝试了什么:
var markerArray=[];
for(i=0;i<latArray.length;i++)
{
markerArray.push("new google.maps.LatLng("+ latArray[i]+","+lngArray[i]+")");
console.log(markerArray[i]);
}
console.log(markerArray[0]);
for(i=0;i<latArray.length;i++)
{
marker = new google.maps.Marker({
position: markerArray[i],
map: map,
title:"This is the place.",
// icon:"phone4.png"
});
var infoWindow = new google.maps.InfoWindow({
content: contentString[i]
});
marker.addListener('click', function(marker,contentString) {
infoWindow.open(map, marker);
});
}
答案 0 :(得分:0)
用地图看看我的功能。它使用来自PHP的一些数据的json对象并将其“转换”为数组,然后将内容添加到多个标记(它实时不是动态的 - 您必须重新加载页面)。此外,它有一个搜索框(打开某些信息窗口)。如果你不明白,请不要犹豫,问:)。
//check if document is fully loaded, seetting a container for ajax call results
$(document).ready(function() {
var tablica = [];
// ajax call for action preparing set of names, descriptions, coords and slugs needed to render deatiled markers on map
$.ajax({
url: 'map/json_prepare',
dataType: 'json',
success: function(response) {
var obj = JSON && JSON.parse(response) || $.parseJSON(response);
obj.forEach(function(item, index, array)
{
tablica.push(item);
});
//call a function rendering a map itself
var map;
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 50.06561980, lng: 19.946850},
zoom: 12
});
////////////////////////////////////////////////////////////////////////////////////////////////////
// LOOP ADDING MARKERS FROM DB WITH PROPER INFO WINDOWS (DESCRIPTION AND LINKS)
// Add a markers reference
var markers = [];
$.each(tablica, function( key, value ) {
//markers
var myLatLng = {lat: value[1], lng: value[2]};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: value[0],
clickable: true,
animation: google.maps.Animation.DROP,
adress: value[5]
});
//infowindows
marker.info = new google.maps.InfoWindow ({
content: '<h1>'+ value[0] + '</h1>' + '<br>' + '<br>' + value[3] + '<br>' + value[5] +'<br>' + '<br>' + '<a href="' + value[4] + '">' + 'Details' + '</a><br/>' +
'<a href="' + 'logged/take-part-in/' + value[4] + '">' + 'Take part in' + '</a><br>'
});
//eventlistener - after click infowindow opens
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
//event listener - after dblclick zoom on certain event is set
google.maps.event.addListener(marker, 'dblclick', function() {
map.setZoom(18);
map.setCenter(marker.getPosition());
});
markers.push(marker);
});
// End of loop adding markers from db.
///////////////////////////////////////////////////////////////////////////////////////////////////////////
///additional event listener - rightclick to get back default zoom
google.maps.event.addListener(map, 'rightclick', function() {
map.setZoom(12);
map.setCenter(map.getPosition());
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CENTRING MAP AS ALL OF MARKERS IS VISIBLE//
//create empty LatLngBounds object
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < tablica.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(tablica[i][1], tablica[i][2]),
map: map
});
//extend the bounds to include each marker's position
bounds.extend(marker.position);
}
//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
///SEARCH_BOX////////
///Here comes part of script adding search box
// Create the search box and link it to the UI element.
// Anchor search box and search button to the map.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
var button = document.getElementById('submitSearch');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(button);
//replacing polish characters on order to search without necessity typing them
function cleanUpSpecialChars(str)
{
str = str.replace(/[Ą]/g,"A");
str = str.replace(/[ą]/g,"a");
str = str.replace(/[Ę]/g,"E");
str = str.replace(/[ę]/g,"e");
str = str.replace(/[Ć]/g,"C");
str = str.replace(/[ć]/g,"c");
str = str.replace(/[Ł]/g,"L");
str = str.replace(/[ł]/g,"l");
str = str.replace(/[Ń]/g,"N");
str = str.replace(/[ń]/g,"n");
str = str.replace(/[Ó]/g,"O");
str = str.replace(/[ó]/g,"o");
str = str.replace(/[Ś]/g,"S");
str = str.replace(/[ś]/g,"s");
str = str.replace(/[Ź]/g,"Z");
str = str.replace(/[ź]/g,"z");
str = str.replace(/[Ż]/g,"Z");
str = str.replace(/[ż]/g,"z");
return str;
}
//Function, that search in array of markers, one which fits the key word written in searchbox.
$('#submitSearch').click(function() {
//Catching searched word and preparing its value for search process
var toSearch = $(input).val().trim();
toSearch = cleanUpSpecialChars(toSearch);
toSearch = toSearch.toLowerCase();
console.log('Szukana fraza -> ' + toSearch);
var results = [];
if (toSearch.length >=3) {
// Iterate through the array
$.each(markers, function (i, marker) {
//preparing certain elemnts of marker objects for search process
markers[i].title = cleanUpSpecialChars(markers[i].title);
markers[i].adress = cleanUpSpecialChars(markers[i].adress);
markers[i].title = markers[i].title.toLowerCase();
markers[i].adress = markers[i].adress.toLowerCase();
if (markers[i].title.indexOf(toSearch) > -1 || markers[i].adress.indexOf(toSearch) > -1) {
results.push(markers[i]);
}
});
if (results.length < 1) {
console.log ('nic');
$('#message2').slideDown(500, function () {
setTimeout(function () {
$('#message2').slideUp(500);
}, 5000);
});
}
// Close all the infoWindows, before rendering Search results.
markers.forEach(function (marker) {
marker.info.close(map, marker);
});
//Opens infWindows for multiple markers found and set bounds so that all markers found are visible
results.forEach(function (result) {
result.info.open(map, result);
bounds.extend(result.position);
});
map.fitBounds(bounds);
}
else{
//what if user has typed less than three characters in searchbox -> render flash mess.
$("#message").slideDown(500, function(){
setTimeout(function(){
$("#message").slideUp(500);
},5000);
});
}
});
//Enabling key Enter for triggering a search action.
$(input).keypress(function(e){
if(e.which == 13){//Enter key pressed
$('#submitSearch').click();//Trigger search button click event
}
});
},
//////////////////////////////////////////////////////////////////////////////////////////
//obsługa błędu, jeśli nie zostanie wyświetlona mapa
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
console.log(ajaxOptions);
alert('Map is broken. Please try again later.')
}
});
});
它不会在这里qork,因为它不包含来自php的数据。
答案 1 :(得分:0)
所以我不会打扰你解释闭包是如何工作的(因为你说你现在对它不感兴趣),我只是为你提供解决方案:
// Your arrays with geo informations
var latArray = [-25.363, -26.263, -25.163];
var lngArray = [131.044, 131.144, 132.044];
// Your array with device information
var deviceIdArray = ["AAA", "BBB", "CCC"];
// Just create map according to the first geo info
var map = new google.maps.Map(document.getElementById("map"), {
center: {lat: latArray[0], lng: lngArray[0]},
zoom: 6
});
// Loop throuhg all geo info
latArray.forEach(function(lat, i) {
// For each one create info window
var infoWindow = new google.maps.InfoWindow({
content: '<div id="content>'
+ '<p style="color:#000000">DeviceID<p>'
+ '<p>'+ deviceIdArray[i] + '</p>'
+'</div>'
});
// For each one create marker
var marker = new google.maps.Marker({
map: map,
position: {lat: latArray[i], lng: lngArray[i]}
});
// Click on the currently created marker will show the right info window
marker.addListener("click", function() {
infoWindow.open(map, marker);
});
});
&#13;
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
&#13;
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map"></div>
&#13;