Мануал как добавить google карты к топику

Многии задаются вопросом как добавить google карту к топику чтобы можно было отмечать точки.
Такой вопрос встал и у меня после неудачного серфинга понял что прийдётся под свои нужды писать самому.

Я думаю многим будет интересно как я это сделал поэтому представляю список всех изменений что я вносил в код.

Оговорюсь сразу делал не через плагины а правил коды. Просто времени на изучение плагинов небыло.

И так приступим

1. В \classes\actions\ActionTopic.class.php после:
$_REQUEST['topic_title']=$oTopic->getTitle();


добавил:
$_REQUEST['coodrinati']=$oTopic->getCoodrinati();



после:
$oTopic->setTextSource(getRequest('topic_text'));


в 2-х местах (добавление и редактирование) добавил:
$oTopic->setCoodrinati(getRequest('coodrinati'));


2. В \classes\modules\topic\entity\Topic.entity.class.php перед:
public function getTags() {
        return $this->_aData['topic_tags'];
    }


добавил:
public function getCoodrinati() {
        return $this->_aData['coodrinati'];
    }


и перед:
public function setTextSource($data) {
        $this->_aData['topic_text_source']=$data;
    }


добавил:
public function setCoodrinati($data) {
        $this->_aData['coodrinati']=$data;
    }


3. В \classes\modules\topic\mapper\Topic.mapper.class.php добавил coodrinati сюда:
public function AddTopic(TopicEntity_Topic $oTopic) {
                $sql = "INSERT INTO ".DB_TABLE_TOPIC." 
                        (blog_id,
                        user_id,
                        topic_type,
                        topic_title, 
                        coodrinati,                   
                        topic_tags,
                        topic_date_add,
                        topic_user_ip,
                        topic_publish,
                        topic_publish_draft,
                        topic_publish_index,
                        topic_cut_text,
                        topic_forbid_comment,
                        topic_text_hash                 
                        )
                        VALUES(?d,  ?d, ?,      ?,      ?,      ?,  ?, ?, ?d, ?d, ?d, ?, ?, ?d, ?)
                ";                      
                if ($iId=$this->oDb->query($sql,$oTopic->getBlogId(),$oTopic->getUserId(),$oTopic->getType(),$oTopic->getTitle(),$oTopic->getCoodrinati(),$oTopic->getTags(),$oTopic->getDateAdd(),$oTopic->getUserIp(),$oTopic->getPublish(),$oTopic->getPublishDraft(),$oTopic->getPublishIndex(),$oTopic->getCutText(),$oTopic->getForbidComment(),$oTopic->getTextHash()))


и сюда:
public function UpdateTopic(TopicEntity_Topic $oTopic) {                
                $sql = "UPDATE ".DB_TABLE_TOPIC." 
                        SET 
                                blog_id= ?d,
                                topic_title= ?,
                                coodrinati = ?,                         
                                topic_tags= ?,
                                topic_date_add = ?,
                                topic_date_edit = ?,
                                topic_user_ip= ?,
                                topic_publish= ?d ,
                                topic_publish_draft= ?d ,
                                topic_publish_index= ?d,
                                topic_rating= ?f,
                                topic_count_vote= ?d,
                                topic_count_read= ?d,
                                topic_count_comment= ?d, 
                                topic_cut_text = ? ,
                                topic_forbid_comment = ? ,
                                topic_text_hash = ? 
                        WHERE
                                topic_id = ?d
                ";                      
                if ($this->oDb->query($sql,$oTopic->getBlogId(),$oTopic->getTitle(),$oTopic->getCoodrinati(),$oTopic->getTags(),$oTopic->getDateAdd(),$oTopic->getDateEdit(),$oTopic->getUserIp(),$oTopic->getPublish(),$oTopic->getPublishDraft(),$oTopic->getPublishIndex(),$oTopic->getRating(),$oTopic->getCountVote(),$oTopic->getCountRead(),$oTopic->getCountComment(),$oTopic->getCutText(),$oTopic->getForbidComment(),$oTopic->getTextHash(),$oTopic->getId())) {


4. Выполнил запрос в базу:
ALTER TABLE `prefix_topic` ADD `coodrinati` varchar(250) default NULL AFTER `topic_forbid_comment`


5. Теперь начинаем править шаблоны: \templates\skin\synio\actions\ActionTopic\add.tpl
после:
{hook run='form_add_topic_topic_end'}

Вставить
<script>
					var vallmappa = '{$_aRequest.coodrinati}';
				</script>
	<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
{literal}
	<script type="text/javascript">
	  var marker;
      var map;
      var markers = [];	
      var geocoder;
  
		$(document).ready(function(){
			initialize();
		});	
			function initialize() {
								geocoder = new google.maps.Geocoder();
								var latlng = new google.maps.LatLng(56.9929, 40.9757);
								var myOptions = {
								  zoom: 12,
								  center: latlng,
								  mapTypeId: google.maps.MapTypeId.ROADMAP,  
									  mapTypeControlOptions: {  
										style: google.maps.MapTypeControlStyle.DROPDOWN_MENU  
								  }  
								};		
								  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

								  google.maps.event.addListener(map, 'click', function(event) {
										setAllMap(null);
										addMarker(event.latLng);
								  });
								  if (vallmappa !='') {
										perr = vallmappa.split(',');
										myLatlng = new google.maps.LatLng(perr[0],perr[1]);
										setAllMap(null);
										addMarker(myLatlng);
								  }						  
				}
					function getAttributeByIndex(obj, index){
					  var i = 0;
					  for (var attr in obj){
						if (index === i){
						  return obj[attr];
						}
						i++;
					  }
					  return null;
					}
								  function setAllMap(map) {
									for (var i = 0; i < markers.length; i++) {
									  markers[i].setMap(map);
									}
								  }					  
								  function addMarker(location) {
									marker = new google.maps.Marker({
									  position: location,
									  map: map
									});
									$('#coodrinati').val(getAttributeByIndex(location,0)+','+getAttributeByIndex(location,1));
									markers.push(marker);
								  }				
			  function codeAddress() {
				var address = document.getElementById('address').value;
				geocoder.geocode( { 'address': address}, function(results, status) {
				  if (status == google.maps.GeocoderStatus.OK) {
						map.setCenter(results[0].geometry.location);
						setAllMap(null);
						addMarker(results[0].geometry.location);				
				  } else {
					alert('Geocode was not successful for the following reason: ' + status);
				  }
				});
			  }			
	</script>
{/literal}	
<p><label for="topic_tags">Введите адрес и нажмите найти:</label>
    <input id="address" type="textbox" class="input-text" value="" style="width: 520px;"/>
    <input type="button" onclick="codeAddress()" class="button" value="Найти"/>
</p>
	
	<label for="topic_tags">Отметьте место на карте:</label>	
	<div id="map_canvas" style="width: 600px; height: 300px;margin-bottom: 10px;"></div>				
<input type="hidden" name="coodrinati" value="{$_aRequest.coodrinati}" id="coodrinati">	


6. Теперь сделаем вывод в топиках: \templates\skin\synio\topic_topic.tpl
после:
	{$oTopic->getText()}
  

Вставляем:
		<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
		<script type="text/javascript">
		    var map;
			$(document).ready(function(){
				initialize();
			});			
			function initialize() {
								vallmappa = '{$oTopic->getCoodrinati()}';
								perr = vallmappa.split(',');
								var latlng = new google.maps.LatLng(perr[0],perr[1]);
								var myOptions = {
								  zoom: 12,
								  center: latlng,
								  mapTypeId: google.maps.MapTypeId.ROADMAP,  
									  mapTypeControlOptions: {  
										style: google.maps.MapTypeControlStyle.DROPDOWN_MENU  
								  }  
								};		
								map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);			
										
										myLatlng = new google.maps.LatLng(perr[0],perr[1]);
										
									marker = new google.maps.Marker({
									  position: myLatlng,
									  map: map
									});										
			}
		</script>		
		<div id="map_canvas" style=" float: left; width:100%; height:200px"></div>	
  


В результате получил:



Хотите поддержать автора топика ?:
DONATE: http://livestreetcms.com/profile/Nick0/donate/
Наши специалисты помогут вам качественно выполнить подключение, установку и ремонт джакузи. Более 20-ти лет на рынке и европейское качество.

11 комментариев

avatar
Спасибо
avatar
ох спасибо реально круто :) забираю
avatar
подставляем
coodrinati=>';alert(12);'
и получаем XSS
  • ort
  • 0
avatar
тогда по мативом исходного кода движка :

vallmappa = '{$oTopic->getCoodrinati()}';

меняем на :
vallmappa = '{$oTopic->getCoodrinati()|escape:'html'}';

я правильно понял?
avatar
Сделал всё по инструкции. Но карта не отображается. Начал копать. Обнаружил, что при редактировании топика, координаты в базу не заносятся с значение по прежнему NULL.
В чём может быть проблема?
avatar
Не все сделали по инструкции что то не так вставили. Получение переменнной или в момент записи. Можите в диску скинуть сайт и фтп я могу глянуть что не так.
avatar
дело в том, что вчера обновил движок до 1.0.2, поэтому в некоторых файлах правил не копипастом, а вручную. В частности, в при создании\изменении топика выбивало ошибку на \classes\modules\topic\mapper\Topic.mapper.class.php, поэтому параметры координат добавлял самостоятельно. В остальном — полный копипаст (за исключением запроса в БД, с учётом своего префикса).
Ну и от себя добавил в шаблон условие: если значение координат null, не отображать блок, так как не во всех блогах карта должна отображаться.
Сейчас в ЛС скину доступ к фтп.
avatar
не могу почему-то в ЛС отправить. пишет «Ошибка: Вам нельзя отправлять инбоксы слишком часто», хотя последнее сообщение было месяц назад. Почистил входящие-исходящие, не помогло ((
avatar
А где происходит получение и запись переменной? Какие участки кода отвечают за этот процесс (в js или в коде движка)? Как можно отследить получение переменных? Попробую покопаться в коде.
avatar
6 — Взять код в
{if $oTopic->getCoodrinati() > 0 }
Код
{else}
нет карты
{/if}


Что бы лишний раз не светилась…
Только зарегистрированные и авторизованные пользователи могут оставлять комментарии.