I have two mysql tables: "cars" and "locations".
Cars are assigned to a locations by having field "location_id" in "cars" table. I am showing locations in a google maps retrieving coordinates from "locations" table.
What I would like to do, is to show in info window of google maps marker (which mark a location) which cars are assigned to this location.
I use get_locations.php with this code to retrieve information from DB:
$query_cars = "SELECT * FROM cars where location_lat not like ''";
$cars = $db->query($query_cars);
$row_cars = $cars->fetchAll(PDO::FETCH_ASSOC);
$query_locations = "SELECT id, name, gpslat, gpslong FROM locations where name not like '%/ Zona%' and status='Activa'";
$locations = $db->query($query_locations);
$rowLocations = $locations->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rowLocations);
Than I call this script from html page with this code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=API KEY">
</script>
<script type="text/javascript">
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.430013, -3.695854),
zoom: 12
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
makeRequest('get_locations.php', function(data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
var image = 'http://www.bluemove.es/equipo/images/car_location_Normal.png';
function displayLocation(location) {
var content = '<div class="infoWindow">' + location.name; // content of the pop up window
if (parseInt(location.gpslat) == 0) {
geocoder.geocode( { 'address': location.address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: location.name,
incon: image
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map,marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(location.gpslat), parseFloat(location.gpslong));
var marker = new google.maps.Marker({
map: map,
position: position,
title: location.name,
icon: image
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map,marker);
});
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
So when marker is clicked, the location name is displayed on the info window. But as I said I also want to display car name that are assigned to this location.
Does anybody have any idea?
Thank you!
You have to make an INNER JOIN query so the $rowLocations will contain both table values.
Something like that:
SELECT * FROM cars AS c INNER JOIN locations AS l ON c.cars = l.location_id
WHERE c.location_lat NOT LIKE "'" AND l.name NOT LIKE '%/ Zona%';
I'm quite new to Google Maps API but while doing some research the other day I saw this.
https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple
Is it as easy as putting php into that contentString
Related
We saw in a similar question that the Places API should return up to 5 results, but right now we are only able to get 1 result. We were following the tutorial to display museums in Sydney. Does anyone know how to display more than one result? The script for the Maps and Places API is below.
let map;
let service;
let infowindow;
function initMap() {
const sydney = new google.maps.LatLng(-33.867, 151.195);
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById("map"), {
center: sydney,
zoom: 15
});
const request = {
query: "Museum",
fields: ["name", "geometry"]
};
service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (let i = 0; i < results.length; i++) {
createMarker(results[i]);
}
map.setCenter(results[0].geometry.location);
}
});
}
function createMarker(place) {
const marker = new google.maps.Marker({
map,
position: place.geometry.location
});
google.maps.event.addListener(marker, "click", () => {
infowindow.setContent(place.name);
infowindow.open(map);
});
}
From the documentation:
Find Place from Query takes a text input and returns a place.
(note the singular "a place")
To get multiple results use nearbySearch (or textSearch)
const sydney = new google.maps.LatLng(-33.867, 151.195);
var request = {
location: sydney ,
radius: '10000',
type: ['museum']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (let i = 0; i < results.length; i++) {
createMarker(results[i]);
}
map.setCenter(results[0].geometry.location);
}
});
proof of concept fiddle
code snippet:
"use strict";
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIwzALxUPNbatRBj3Xi1Uhp0fFzwWNBkE&libraries=places">
let map;
let service;
let infowindow;
function initMap() {
const sydney = new google.maps.LatLng(-33.867, 151.195);
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById("map"), {
center: sydney,
zoom: 15
});
var request = {
location: sydney ,
radius: '10000',
type: ['museum']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log("places service returned "+results.length+" results");
document.getElementById('info').innerHTML = "places service returned "+results.length+" results";
for (let i = 0; i < results.length; i++) {
createMarker(results[i]);
}
map.setCenter(results[0].geometry.location);
}
});
}
function createMarker(place) {
const marker = new google.maps.Marker({
map,
position: place.geometry.location
});
google.maps.event.addListener(marker, "click", () => {
infowindow.setContent(place.name);
infowindow.open(map);
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 90%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Place Searches</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=places&v=weekly"
defer
></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="info"></div>
<div id="map"></div>
</body>
</html>
So I am trying to make a simple application that will allow the user to search for restaurants and have the results show as markers on the map and as text below. The results object that returns from the textSearch doesn't provide detailed information like: phone number, pictures, etc. So i decided to create an array of place id's pushed from the results object, get the place details for each id, then push that into an array. The problem I get is a message from google saying I'm over my quota and I think it's because I'm requesting the place details for every single search result.
Is there a way I can request the place details only for the marker I click? Or is there a better solution to my problem? Thank you in advance for your help.
<!DOCTYPE html>
<html>
<head>
<title>gMap test</title>
<style type="text/css">
#map-canvas{
height:500px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script type="text/javascript">
function performSearch(){
var locationBox;
var address = document.getElementById("address").value;
var searchRadius = metricConversion(document.getElementById("radius").value);
//gMaps method to find coordinates based on address
geocoder.geocode({'address':address}, function(results,status){
if(status == google.maps.GeocoderStatus.OK){
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map:map,
position: results[0].geometry.location
});
var latitude = results[0].geometry.location.A;
var longitude = results[0].geometry.location.F;
locationBox = new google.maps.LatLng(latitude, longitude);
}else{
errorStatus(status);
return;
}
//search request object
var request = {
query: document.getElementById('keyword').value,
location: locationBox,
radius: searchRadius,
//minPriceLvl: minimumPrice,
//maxPriceLvl: maximumPrice,
types: ["restaurant"]
}
//search method. sending request object and callback function
service.textSearch(request, handleSearchResults);
});
};
var latLngArray = [];
var placeIdArray = [];
//callback function
function handleSearchResults(results,status){
if( status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
placeIdArray.push(results[i].place_id)
latLngArray.push(results[i].geometry.location);
};
for(var j = 0; j<placeIdArray.length; j++){
service.getDetails({placeId: placeIdArray[j]},getDetails)
};
}
else{errorStatus(status)};
};
var detailedArray = [];
function getDetails(results,status){
if (status == google.maps.places.PlacesServiceStatus.OK) {
detailedArray.push(results);
for(var i = 0; i<detailedArray.length; i++){
createMarker(detailedArray[i],i);
}
}
else{
errorStatus(status)
};
}
//array of all marker objects
var allMarkers = [];
//creates markers and info windows for search results
function createMarker(place, i) {
var image = 'images/number_icons/number_'+(i+1)+'.png';
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
html:
"<div class = 'markerPop'>" + "<h3>" + (i+1) + ". " + place.name + "</h3><br>" + "<p>Address: "
+ place.formatted_address + "</p><br>" + "<p> Price Range: "+ priceLevel(place.price_level)
+ "</p>" + "</div>",
icon: image
});
allMarkers.push(marker);
marker.infowindow = new google.maps.InfoWindow();
//on marker click event do function
google.maps.event.addListener(marker, 'click', function() {
//service.getDetails({placeId: placeIdArray[j]},getDetails)
//sets infowindow content and opens infowindow
infowindow.setContent(this.html);
infowindow.open(map,this);
});
//create new bounds object
var bounds = new google.maps.LatLngBounds();
//iterates through all coordinates to extend bounds
for(var i = 0;i<latLngArray.length;i++){
bounds.extend(latLngArray[i]);
};
//recenters map around bounds
map.fitBounds(bounds);
};
var map;
var service;
var geocoder;
var infowindow;
function initialize(location){
var mapOptions = {
center: new google.maps.LatLng(37.804, -122.271),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
service = new google.maps.places.PlacesService(map)
infowindow = new google.maps.InfoWindow();
};
$(document).ready(function(){
initialize();
$('#search').on('click', function(){
removeMarkers();
performSearch();
});
});
//::::::Random Functions:::::::
//Clears all markers between searches
function removeMarkers(){
for(var i = 0; i<allMarkers.length;i++){
allMarkers[i].setMap(null);
};
};
//converts miles to meters for search object
function metricConversion(miles){
var meters;
meters = miles * 1609.34;
return meters;
}
//converts number value to $ sign
function priceLevel(number){
var moneySigns = ""
for(var i =0;i<=number;i++){
moneySigns += "$";
};
return moneySigns;
}
//errors for search results
function errorStatus(status){
switch(status){
case "ERROR": alert("There was a problem contacting Google Servers");
break;
case "INVALID_REQUEST": alert("This request was not valid");
break;
case "OVER_QUERY_LIMIT": alert("This webpage has gone over its request quota");
break;
case "NOT_FOUND": alert("This location could not be found in the database");
break;
case "REQUEST_DENIED": alert("The webpage is not allowed to use the PlacesService");
break;
case "UNKNOWN_ERROR": alert("The request could not be processed due to a server error. The request may succeed if you try again");
break;
case "ZERO_RESULTS": alert("No result was found for this request. Please try again");
break;
default: alert("There was an issue with your request. Please try again.")
};
};
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="searchBar">
<h3>search options</h3>
Location:<input type="text" id="address" value="enter address here" /><br>
Keyword<input type="text" id="keyword" value="name or keyword" /><br>
Advanced Filters:<br>
Search Radius:<select id="radius">
<option>5</option>
<option>10 </option>
<option>15 </option>
<option>20 </option>
<option>25 </option>
</select>miles<br>
<div id="minMaxPrice">
Min Price<select id="minPrice">
<option>$</option>
<option>$$</option>
<option>$$$</option>
<option>$$$$</option>
</select>
Max Price<select id="maxPrice">
<option>$</option>
<option>$$</option>
<option>$$$</option>
<option>$$$$</option>
</select>
</div>
<input type="button" id="search" value="Submit Search"/><br>
</div>
<div id='searchResults'>
</div>
</body>
</html>
The radarSearch example in the documentation requests the details of the marker on click.
code snippet:
var map;
var infoWindow;
var service;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-33.8668283734, 151.2064891821),
zoom: 15,
styles: [{
stylers: [{
visibility: 'simplified'
}]
}, {
elementType: 'labels',
stylers: [{
visibility: 'off'
}]
}]
});
infoWindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
keyword: 'best view'
};
service.radarSearch(request, callback);
}
function callback(results, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
for (var i = 0, result; result = results[i]; i++) {
createMarker(result);
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: {
// Star
path: 'M 0,-24 6,-7 24,-7 10,4 15,21 0,11 -15,21 -10,4 -24,-7 -6,-7 z',
fillColor: '#ffff00',
fillOpacity: 1,
scale: 1 / 4,
strokeColor: '#bd8d2c',
strokeWeight: 1
}
});
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(place, function(result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
var htmlStr = "<b>"+result.name+"</b><br>";
if (result.website) htmlStr += "<a href='"+result.website+"'>"+result.website+"</a><br>";
if (result.adr_address) htmlStr += result.adr_address+"<br>";
infoWindow.setContent(htmlStr);
infoWindow.open(map, marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<div id="map-canvas"></div>
I had the same issue some time ago. The geocoding function by google is done in order to avoid the user executing it on a large set of data (and then, avoid you to get a large amount of geocoded address easily).
My solution was to execute the geocoding function only when the user choose a particular place, and then, display this particular data (handled by the click on the pin).
I think it would be very useful to initiate a jsfiddle with a working version of your code.
Basically on your function :
google.maps.event.addListener(marker, 'click', function() {
//Execute geocoding function here on marker object
//Complete your html template content
infowindow.setContent(this.html);
infowindow.open(map,this);
});
I have a script(get_search_data.php) that performs search from the database based on the keyword fname. i wish that according to the search result, locations should get displayed on the map (display_map.php) along with the marker and popup window for information.
table view for features_for_office
id fname co_address_line1 co_address_line2 lat lon
get_search_data.php
<?php
require 'config.php';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$fname = $_POST['fname'];
$sth = "SELECT * FROM features_for_office WHERE fname LIKE :fname ";
$stmt = $db->prepare($sth);
$stmt->bindValue(':fname', '%' . $fname . '%', PDO::PARAM_STR);
$stmt->execute();
$locations = $stmt->fetchAll();
echo json_encode( $locations );
} catch (Exception $e) {
echo $e->getMessage();
}
?>
<script src="jquery-1.11.1.js"></script>
<script>
$(document).ready(function(){
$('#drop2').on('change',function(){
//var fname = $(this).val();
var fname = $(this).find('option:selected').text();
// rename your file which include $fname with get_search_data.php
if(fname !== ""){
$.post('display_map.php',{fname: fname},function(data){
$('.showsearch').html(data);
});
}
});
});
</script>
display_map.php
<style type="text/css">
#main { padding-right: 15px; }
.infoWindow { width: 220px; }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function makeRequest(url, callback)
{
var request;
if (window.XMLHttpRequest)
{
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
}
else
{
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function()
{
if (request.readyState == 4 && request.status == 200)
{
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
var map;
// Ban Jelačić Square - City Center
var center = new google.maps.LatLng(21.0000, 78.0000);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function init()
{
var mapOptions =
{
zoom: 6,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
makeRequest('get_search_data.php', function(data)
{
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++)
{
displayLocation(data[i]);
}
});
}
function displayLocation(location)
{
var content = '<div class="infoWindow"><strong>' + location.fname + '</strong>'
+ '<br/>' + location.co_address_line1
+ '<br/>' + location.co_address_line2 + '</div>';
if (parseInt(location.lat) == 0)
{
geocoder.geocode( { 'address': location.co_address_line1 }, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var marker = new google.maps.Marker
({
map: map,
position: results[0].geometry.location,
title: location.name
});
google.maps.event.addListener(marker, 'click', function()
{
infowindow.setContent(content);
infowindow.open(map,marker);
});
}
});
}
else
{
var position = new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lon));
var marker = new google.maps.Marker
({
map: map,
position: position,
title: location.name
});
google.maps.event.addListener(marker, 'click', function()
{
infowindow.setContent(content);
infowindow.open(map,marker);
});
}
}
</script>
</head>
<body onload="init();">
<section id="main">
<div id="map_canvas" style="width: 70%; height: 500px;"></div>
</section>
</body>
Although the map gets displayed but the markers are not getting displayed. would appreciate any help
It might be strange answer, but your code should work.
But if you mix up lat and lon in your database markers would still display but you won't see them because they appear in another part of the world.
If I am wrong please post the the structure of json response from php script
I need to create a php page that shows, for each address contained in an array, a Google map.
The code I wrote is wrong, what I see is a column of grey maps except the last maps, that contains a lot of markers.
Instead, what I would like is a list of maps each with a single marker.
The array of addresses is taken from the database using php, this array is then passed to javascript using the function json_encode.
I hope this image can help you better understand what I want and what I get with my code instead enter link description here
Code HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="../public/css/style.css"/>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type='text/javascript'>
var addresses = <?php echo json_encode($addresses); ?>;
</script>
<script type="text/javascript" src="../public/js/maps.js"></script>
</head>
<body>
<!-- mappe Google -->
<div id="content_map-canvas">
</div>
</body>
</html>
Code javascript:
function initialize() {
var count = -1; //Is used to number the div (one per address)
var descriptions = new Array(); //Array of descriptions
//I copy the contents of the addresses array in the descriptions array
for(var i=0; i<addresses.length; i++) {
var address = addresses[i];
var description = addresses[i];
var geoc = "geocoder" + i;
eval("var " + geoc);
var map = "map" + i;
eval("var " + map);
geoc = new google.maps.Geocoder();
var options = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
count = count + 1;
var id = "map-canvas" + count;
var div = document.createElement("div");
div.id = id;
div.style.width= "300px";
div.style.height= "300px";
var content_map_canvas = document.getElementById("content_map-canvas");
content_map_canvas.appendChild(div);
map = new google.maps.Map(document.getElementById(id), options);
geoc.geocode({'address': address}, function(results, status) {
if(status === google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker
({map: map,
position: results[0].geometry.location,
title: description
});
marker.setAnimation(google.maps.Animation.DROP);
contentString = description;
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
else {
alert("Geocode failed: " + status + ", " + address);
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Where am I wrong? Thanks
Closure problem. All markers are set to last map from for loop and also only the last map from the list is properly defined. You have to enclose your geocode part in:
...
(function(address, map) {
geoc.geocode({'address': address}, function(results, status) {
console.log(address + ', status: ' + status);
if (status === google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker
({map: map,
position: results[0].geometry.location,
title: description
});
marker.setAnimation(google.maps.Animation.DROP);
contentString = description;
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
else {
alert("Geocode failed: " + status + ", " + address);
}
});
})(address, map)
...
I have some issues with Google maps api v3. I managed to create a map where new markers are displayed when the user drag the map. However, it do not delete the past markers. I have read many tutorials and thread (especially this one: Google Maps V3: Updating Markers Periodically) without success.
Here is my main page:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Développez avec les API Google Maps</title>
<style type="text/css">
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
padding: 0px;
}
#map_canvas {
height: 100%;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
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.onreadystatechange = function() {
if (request.readyState == 4) {
try {
status = request.status;
} catch (e) {
}
if (status == 200) {
callback(request.responseText, request.status);
request.onreadystatechange = function() {};
}
}
}
request.open('GET', url, true);
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);
}
var map;
function initialize() {
var latlng = new google.maps.LatLng(46.7, 2.5);
var myOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
downloadUrl("getPoi2.php", function(data) {
var xml = xmlParse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
createMarker(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")), markers[i].getAttribute('titre'));
}
});
/* Ici, on ajoute l'écouteur d'événement suite à un glisser / déposer */
google.maps.event.addListener(map, 'dragend', function() {
var bds = map.getBounds();
var South_Lat = bds.getSouthWest().lat();
var South_Lng = bds.getSouthWest().lng();
var North_Lat = bds.getNorthEast().lat();
var North_Lng = bds.getNorthEast().lng();
downloadUrl("getPoi.php?maxlat="+North_Lat+"&minlat="+South_Lat+"&minlong="+South_Lng+"&maxlong="+North_Lng, function(data) {
var xml = xmlParse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
createMarker(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")), markers[i].getAttribute('titre'));
}
});
});
}
function createMarker(lat, lng, titre){
var latlng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: titre
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 100%; height: 100%;"></div>
</body>
</html>
And there is my getPoin.php:
<?php
$user = "root";
$password = "";
$host = "localhost";
$bdd = "citiesinvaders";
mysql_connect($host,$user,$password);
mysql_select_db($bdd) or die("erreur de connexion à la base
de données");
$sql = "SELECT * FROM location order by city desc limit 1";
$res = mysql_query($sql) or die(mysql_error());
$dom = new DomDocument('1.0', 'utf-8');
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
while ($result = mysql_fetch_array($res)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("city", $result["city"]);
$newnode->setAttribute("lat", $result["latitude"]);
$newnode->setAttribute("lng", $result["longitude"]);
}
$xmlfile = $dom->saveXML();
echo $xmlfile;
?>
Thank you for your help!
Keep track of the google.maps.Marker objects created, delete them before creating new ones.
var map;
var gmarkers = [];
/* Ici, on ajoute l'écouteur d'événement suite à un glisser / déposer */
google.maps.event.addListener(map, 'dragend', function() {
var bds = map.getBounds();
var South_Lat = bds.getSouthWest().lat();
var South_Lng = bds.getSouthWest().lng();
var North_Lat = bds.getNorthEast().lat();
var North_Lng = bds.getNorthEast().lng();
downloadUrl("getPoi.php?maxlat="+North_Lat+"&minlat="+South_Lat+"&minlong="+South_Lng+"&maxlong="+North_Lng, function(data) {
var xml = xmlParse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
// hide and delete the existing markers
for (var i=0; i<gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
gmarkers = [];
for (var i = 0; i < markers.length; i++) {
createMarker(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")), markers[i].getAttribute('titre'));
}
});
});
function createMarker(lat, lng, titre){
var latlng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: titre
});
// keep a reference to created markers so you can remove them
gmarkers.push(marker);
}
This is based on my understanding of your question... To clarify... When the map is moved the markers are placed over the old markers? A.K.A. They are 'doubling up' on map drag?
Create an array to hold the markers.
var markers = [];
Then, add the markers to the array in 'createMarker()' function. Also, check to see if a marker has already been created, and if so, do not recreate.
function createMarker(lat, lng, titre) {
for( marker in markers ) {
var coord = marker.getgetPosition();
if( coord.lat() == lat && coord.lng() == lng )
return;
}
var latlng = new google.maps.LatLng(lat, lng);
markers.push( new google.maps.Marker({
position: latlng,
map: map,
title: titre
}));
}