У меня есть этот код, который устанавливает несколько маркеров, и я новичок в API Карт Google, и пытаюсь узнать, как настроить карту для автоматического отображения маркера местоположения текущего пользователя. Учебник, который я получаю, задает центр карты после получения всех маркеров. Вот мой код: -Перейти к пользовательскому указателю местоположения
<script>
var startPos, positionPromise = $.Deferred();
navigator.geolocation.getCurrentPosition(function(position) {
startPos = position;
$('#pok_lat').val(startPos.coords.latitude);
$('#pok_long').val(startPos.coords.longitude);
positionPromise.resolve();
}, function(error) {
alert('Error occurred. Error code: ' + error.code + '');
// error.code can be:
// 0: unknown error
// 1: permission denied
// 2: position unavailable (error response from locaton provider)
// 3: timed out
positionPromise.reject();
});
$(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "//maps.googleapis.com/maps/api/js?key=SOMEAPIKEY&callback=initialize";
document.body.appendChild(script);
});
window["initialize"] = function() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers LatLong
$.when(positionPromise).then(function(){
var lats = document.getElementById("pokemon_lat").value;
var longi = document.getElementById("pokemon_long").value;
console.log('Lat:'+lats+' Long:'+longi);
var markers = [
['You are here!', lats,longi],
<?php
for ($x = 0; $x < count($pok_info); $x++) {
if ($x < count($pok_info)) {
$addcomma = ",";
}
else {
$addcomma = "";
}
$pok_array[] = "['".$pok_info[$x]['name']."', ".$pok_info[$x]['lat'].",".$pok_info[$x]['long']."]".$addcomma;
}
$remove_comma = count($pok_array);
$remove_comma = $remove_comma - 1;
$pok_array[$remove_comma] = rtrim($pok_array[$remove_comma],',');
foreach ($pok_array as $value) {
echo $value;
}
?>
];
// Info Window Content
var infoWindowContent = [
['You are here!'],
<?php
for ($x = 0; $x < count($pok_info); $x++) {
if ($x < count($pok_info)) {
$addcomma = ",";
}
else {
$addcomma = "";
}
$pok_array_info[] = "['<div class=\"info_content\"><h3>".$pok_info[$x]['name']."</h3><br><img width=\"100\" height=\"100\" src=\"".$pok_info[$x]['pic']."\"><p>".$pok_info[$x]['description']."</p>']".$addcomma;
}
$remove_comma = count($pok_array_info);
$remove_comma = $remove_comma - 1;
$pokemon_array_info[$remove_comma] = rtrim($pok_array_info[$remove_comma],',');
foreach ($pok_array_info as $value) {
echo $value;
}
?>
];
// Pok Icons
var pokeImage = [
['images/pokeball.png'],
<?php
$img_icons = array();
for ($x = 0; $x < count($pok_info); $x++) {
$img_icon = $pok_info[$x]['pic'];
$img_icon = explode(".",$img_icon);
$img_icons[] = $img_icon[0]."_small.png";
$addcomma = ",";
$pok_array_info_pic[] = "['".$img_icons[$x]."']".$addcomma;
}
$remove_comma = count($pok_array_info_pic);
$remove_comma = $remove_comma - 1;
$pok_array_info[$remove_comma] = rtrim($pok_array_info_pic[$remove_comma],',');
foreach ($pok_array_info_pic as $value) {
echo $value;
}
?>
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for(i = 0; i < markers.length; i++) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
icon: pokeImage[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
map.panTo(marker.getPosition());
// Automatically center the map fitting all markers on the screen
//map.fitBounds(bounds);
//console.log('Lat:'+lats)+' Long:'+parseInt(longi));
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}, function(){
console.log("Could not get latitude and longitude)-:");
});
}
</script>
Мне удалось получить местоположение пользователя, просто как я могу просто центрировать карту местоположения пользователя? На карте будет много других маркеров, но я просто хочу сосредоточить маркер местоположения пользователя. Вы понимаете, что я имел в виду? – MuthaFury
Okij, поэтому перед нанесением карты вам нужно перевести все маркер, присутствующие в вашей базе данных, где вы можете проверить и передать эту долготу широты в drawmap mthod. – mean
var mapOptions = {zoom: 7, center: latlng, mapTypeId: google.maps. MapTypeId.ROADMAP, mapTypeControl: false}; Я отдал центр опций: latlng, который будет сосредоточен на дате широты долготы в Map – mean