Google Maps API v3 - PHP - MYSQL
-
08-07-2019 - |
Pergunta
Google Maps API V3 é o que eu estou tentando usar.
Eu tenho todas as coordenadas no mysql. Eu apenas, por exemplo, necessidade de tomar 5 listas e colocá-los em um mapa, mas eu gostaria de ser capaz de encontrar o ponto central baseado nas múltiplas coordenadas que eu gostaria de exibir, e o nível de zoom bem. Sim saber?
Eu estou tendo o tempo da minha vida com algo que eu sei é terrivelmente simples, eu simplesmente não consigo descobrir isso API. Vou paypal $ 20 a qualquer um que pode me ajudar.
//select * from mysql limit 5
//ok great we got 5 results, great job, format the 5 results so google maps like it, [name,lat,lng] whatever.
//put them on the map and let them be clickable so i can put stuff in the infowindow thing
//make the map adjust to the proper zoom level and center point
Atualização
Isto é o que eu estava procurando, espero que isso ajude os outros.
crédito para [Chris B] para a fórmula matemática do senso comum para obter o coord centro, o cabo sw é o menor lat e lon, eo ne coord é o maior lat e lon
sort($lat)&&sort($lon);
$r['c'] = array_sum($lat)/count($lat).', '.array_sum($lon)/count($lon);
$r['ne'] = $lat[count($lat)-1].', '.$lon[count($lon)-1];
$r['sw'] = $lat[0].', '.$lon[0];
var myOptions = {zoom:4,center: new google.maps.LatLng(<?php echo $r['c']; ?>),mapTypeId:google.maps.MapTypeId.ROADMAP}
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
<?php foreach($x as $l) echo 'new google.maps.Marker({position:new google.maps.LatLng('.$l['lat'].','.$l['lon'].'),map:map,clickable:true});'; ?>
map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(<?php echo $r['sw']; ?>),new google.maps.LatLng(<?php echo $r['ne']; ?>)));
Solução
Se um ponto central médio / ponderada é aceitável - você poderia apenas média todas as latitudes e média todas as longitudes:
$latTotal = 0;
$lngTotal = 0;
foreach ($markers as $marker) {
$latTotal += $marker['lat'];
$lngTotal += $marker['lng'];
}
$centerLat = $latTotal/count($markers);
$centerLng = $lngTotal/count($markers);
Para o resto, há alguns boa V3 tutoriais no Google .
Outras dicas
Eu estava usando o Google Maps v3 um mês ou dois para trás, mas mudou para v2 mais tarde. No entanto, eu tive o mesmo problema como você então eu escrevi uma classe MarkerManager para v3 API. Não consigo encontrar a versão mais recente da minha classe, mas eu fiz encontrar um, espero, trabalhando um. Você pode obtê-lo aqui .
Eu tenho que avisá-lo embora - não é optimazed em tudo e não está usando sobreposições, então quando eu tentei colocar 50+ marcadores no gerenciador de e alternado a ocultar / mostrar a classe é sloooow ... Mas talvez você pode ter algum sucesso com ele.
Exemplo de uso:
var map = new google.maps.Map(document.getElementById('MapLayerId'), {
zoom: 7,
position: new google.maps.LatLng(latitude, longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker1 = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map
});
var marker2 = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map
});
var manager = new MarkerManager(map, {fitBounds: true});
manager.add(marker1);
manager.add(marker2);
manager.show();
GDownloadUrl em V2 downloadURL equivalente na API do Google Maps V3
Como colocar todas as coordenadas no banco de dados (MySQL ou SQL).
var myLatlng = new google.maps.LatLng("37.427770" ,"-122.144841");
var myOptions = {zoom: 15, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP,}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var url='marker.php?arg1=x&arg2=y...';
downloadUrl(url, function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = new google.maps.Marker({position: latlng, map: map});
}
});
function createXmlHttpRequest() {
try {
if (typeof ActiveXObject != 'undefined') {
return new ActiveXObject('Microsoft.XMLHTTP');
} else if (window["XMLHttpRequest"]) {
return new XMLHttpRequest();
}
} catch (e) {
changeStatus(e);
}
return null;
};
function downloadUrl(url, callback) {
var status = -1;
var request = createXmlHttpRequest();
if (!request) {
return false;
}
request.open('GET', url);
request.onreadystatechange = function() {
if (request.readyState == 4) {
try {
status = request.status;
} catch (e) {
// Usually indicates request timed out in FF.
}
if (status == 200) {
var s=request.responseText;
callback( xmlParse(s) );
}
}
}
try {
request.send(null);
}catch (e) {
changeStatus(e);
}
};
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
Você check-out o mapa oficial do Google PHP / Mysql tutorial? http://code.google.com/apis/maps/articles/phpsqlajax. html
Tente este algoritmo para encontrar o centróide de um polígono:
http://tog.acm.org/resources/GraphicsGems/gemsiv /centroid.c