@Caitiff_One
Обычный человек, начинающий разработчик:)

Как избавиться от одинаковых заголовков маркеров в google maps api?

Привет всем, скажу сразу, я не специализируюсь на JS и т.д., так что возможно мой вопрос глупый, но тем не менее, я достаточно долго гуглил, искал на stackoverflow и т.д., но ответа так и не нашёл.

Делаю небольшую страничку, в которой смогу выбрать текстовый файл (содержимое - куча строк вида "ЗаголовокДляМаркера";"АдресСтрокой"), нажимать на кнопку и создавать для каждой строки маркер на карте с соответствующим примечанием, которое будет всплывать при нажатии на маркер. Несколько маркеров у меня создаётся, но вот заголовок ко всем пишется от последнего:( не знаю что уже поделать.

Подскажите, пожалуйста, где хотя бы почитать?:)

Ещё есть проблема с тем, как обойти лимит гугла на 10 запросов в секунду? я попытался сделать задержку, но всё равно ругается.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Google Map Template with Geocoded Address</title>
	<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>		<!-- Google Maps API -->
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>	<!-- Google CDN for jQuery -->
	<script>
	var map;	// Google map object
	
	// Initialize and display a google map
	$(function() {  
		// Create a Google coordinate object for where to initially center the map
		var latlng = new google.maps.LatLng( 55.7520263,37.6153107);//38.8951, -77.0367 );	// Washington, DC
		
		// Map options for how to display the Google map
		var mapOptions = { zoom: 12, center: latlng  };
		
		// Show the Google map in the div with the attribute id 'map-canvas'.
		map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

		// Update the Google map for the user's inputted address
		$( "#locate" ).click( function( event ) {
			var geocoder = new google.maps.Geocoder();    // instantiate a geocoder object
			
			// Get the user's inputted address
			var address = document.getElementById( "address" ).value;
		
			// Make asynchronous call to Google geocoding API
			geocoder.geocode( { 'address': address }, function(results, status) {
				var addr_type = results[0].types[0];	// type of address inputted that was geocoded
				if ( status == google.maps.GeocoderStatus.OK ) 
					ShowLocation( results[0].geometry.location, address);
				else     
					alert("Geocode was not successful for the following reason: " + status);        
			});
		} );

		// FILE TEST!!!
		if (window.File && window.FileReader && window.FileList && window.Blob) {
		    var fileSelected = document.getElementById('txtfiletoread');
		    fileSelected.addEventListener('change', function (e) { 
		         //Set the extension for the file 
		         var fileExtension = /text.*/; 
		         //Get the file object 
		         var fileTobeRead = fileSelected.files[0];
		        //Check of the extension match 
		         if (fileTobeRead.type.match(fileExtension)) { 
		             //Initialize the FileReader object to read the 2file 
		             var fileReader = new FileReader(); 
		             fileReader.onload = function (e) { 
		                 var fileContents = document.getElementById('filecontents'); 
		                 fileContents.innerText = fileReader.result; 
		             } 
		             fileReader.readAsText(fileTobeRead); 
		         } 
		         else { 
		             alert("Please select text file"); 
		         }
		 
		    }, false);
		} 
		 else { 
		     alert("Files are not supported"); 
		 }
 		// FILE TEST!!!

 		function sleep(ms) 
 		{
			ms += new Date().getTime();
			while (new Date() < ms){}
		} 
		
		// loads all the adresses and places markers on the map
		$("#load_all").click(function(event)
		{
			var geocoder = new google.maps.Geocoder();    // instantiate a geocoder object

			var fileContents = document.getElementById('filecontents'); 

			var lines = fileContents.innerText.split('\n');

			for(var i = 0; i<lines.length; i++)
			{
				lines[i] = lines[i].split(';');
			}

			for (var i = 0; i<lines.length; i++)
			{
				sleep(102);

				var PersonalData = lines[i][0];

				geocoder.geocode( { 'address': lines[i][1] }, function(results, status) {
					if ( status == google.maps.GeocoderStatus.OK ) 
						ShowLocation(results[0].geometry.location, PersonalData);
					else     
						alert("Geocode was not successful for the following reason: " + status);        
				});
			}
		});
	} );
	
	function bindInfoWindow(marker, map, infowindow, html) {
	    google.maps.event.addListener(marker, 'click', function() {
	        infowindow.setContent(html);
	        infowindow.open(map, marker);
	    });
	} 

	// Show the location (address) on the map.
	function ShowLocation( latlng, PersonalData)
	{	
		// Place a Google Marker at the same location as the map center 
		// When you hover over the marker, it will display the title
		var marker = new google.maps.Marker( { 
			position: latlng,     
			map: map,      
			title: PersonalData
		});
		
		// Create an InfoWindow for the marker
		var contentString = "<b>" + PersonalData + "</b>";	// HTML text to display in the InfoWindow
		var infowindow = new google.maps.InfoWindow( { content: contentString } );
		
		// Set event to display the InfoWindow anchored to the marker when the marker is clicked.
		//google.maps.event.addListener( marker, 'click', function() { infowindow.open( map, marker ); });
		bindInfoWindow(marker, map, infowindow, PersonalData);
	}

	</script>
	<style>
	/* style settings for Google map */
	#map-canvas
	{
		width : 1024px; 	/* map width */
		height: 768px;	/* map height */
	}
	</style>
</head>
<body>
	<!-- Dislay Google map here -->
	<div id='map-canvas' ></div><br/>
	<div>
		<label for="address"> Address:</label>
		<input type="text" id="address"/>
		<button id="locate">Locate</button>
		<button id="load_all">Load all adresses</button>
		<hr/>
		 Please Select text file of which contents are to be read: 
      	<input type="file" id="txtfiletoread" />
    	<div>The File Contents are as below:</div> 
     	<div id="filecontents">
    	</div>
		</div>
</body>
</html>


Буду признателен за любую помощь:)
  • Вопрос задан
  • 314 просмотров
Пригласить эксперта
Ответы на вопрос 1
Зачем вам нужен параметр html в функции bindInfoWindow?
Вытащите данные из параметра marker. Например с помощью метода
marker.getTitle()
Это должно решить проблему.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы