使用 Javascript 变量放置 Google 地图标记位置
Putting a Google Maps Marker position with a Javascript variable
我试图在我的地图中放置一个标记,当我复制警报结果(例如:{lat:-25.4025,lng:-49.2643})并直接放在 'position' 字段中它工作正常,但是当我把变量放在上面时,它没有。
PHP
$History_Assoc = mysqli_fetch_array($HistoryQuery);
echo '<ul class="repoFolder" data-value=" {lat: '.(float)$History_Assoc['latitude'].', lng: '.(float)$History_Assoc['longitude'] .'} ">';
echo '<br>';
JAVASCRIPT
var folders = document.getElementsByClassName("repoFolder");
for (let i = 0; i < folders.length; i++) {
folders[i].onclick = function() {rootFolder.call(this)}; // note that I am passing in the context to rootFolder.
}
function rootFolder() {
var variable = this.getAttribute('data-value');
alert(variable);
var markersHistory = new google.maps.Marker({
position: variable,
map: map,
icon: iconBlue2,
});
}
从您的标记中的数据值属性解析 JSON 时似乎出现问题。有几种方法可以处理这个问题,但我认为最简单的方法是将纬度和经度值作为两个单独的数据属性嵌入,然后使用 Google Maps LatLng 对象指定标记的坐标。这样您就可以避免各种 JSON 陷阱。这是一个例子:
HTML:
<ul class="repoFolder" data-lat="-25.4025" data-lng="-49.2643">
<li>Clicky</li>
</ul>
Javascript
function rootFolder()
{
var latitude = this.getAttribute('data-lat');
var longitude = this.getAttribute('data-lng');
var latLng = new google.maps.LatLng(latitude, longitude);
var markersHistory = new google.maps.Marker({
position: latLng,
map: map
});
}
我试图在我的地图中放置一个标记,当我复制警报结果(例如:{lat:-25.4025,lng:-49.2643})并直接放在 'position' 字段中它工作正常,但是当我把变量放在上面时,它没有。
PHP
$History_Assoc = mysqli_fetch_array($HistoryQuery);
echo '<ul class="repoFolder" data-value=" {lat: '.(float)$History_Assoc['latitude'].', lng: '.(float)$History_Assoc['longitude'] .'} ">';
echo '<br>';
JAVASCRIPT
var folders = document.getElementsByClassName("repoFolder");
for (let i = 0; i < folders.length; i++) {
folders[i].onclick = function() {rootFolder.call(this)}; // note that I am passing in the context to rootFolder.
}
function rootFolder() {
var variable = this.getAttribute('data-value');
alert(variable);
var markersHistory = new google.maps.Marker({
position: variable,
map: map,
icon: iconBlue2,
});
}
从您的标记中的数据值属性解析 JSON 时似乎出现问题。有几种方法可以处理这个问题,但我认为最简单的方法是将纬度和经度值作为两个单独的数据属性嵌入,然后使用 Google Maps LatLng 对象指定标记的坐标。这样您就可以避免各种 JSON 陷阱。这是一个例子:
HTML:
<ul class="repoFolder" data-lat="-25.4025" data-lng="-49.2643">
<li>Clicky</li>
</ul>
Javascript
function rootFolder()
{
var latitude = this.getAttribute('data-lat');
var longitude = this.getAttribute('data-lng');
var latLng = new google.maps.LatLng(latitude, longitude);
var markersHistory = new google.maps.Marker({
position: latLng,
map: map
});
}