google map markers performance - google-maps

on my web site http://offersmapper.com/
i have a map that has to show from 2000 to 5000 markers. is really slow.
i tried with markercluster as suggested but nothing... most probably i'm doing something wrong... any one that can help me?:
function initialize() {
var mapOptions = {
zoom: <? echo $zoom; ?>,
center: new google.maps.LatLng(<? echo $lat ?>, <? echo $lng ?>),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var markers_1 = [];
<?
while($deal=mysql_fetch_assoc($query))
{
$t="
var contentString".$deal['id']."='".$info."';
var InfoWin".$deal['id']."= new google.maps.InfoWindow({
content: contentString".$deal['id'].",
maxWidth: 300
});
var marker".$deal['id']." = new google.maps.Marker({
position: new google.maps.LatLng(".$deal['lat'].", ".$deal['lng']."),
icon: ".$icon."
});
google.maps.event.addListener(marker".$deal['id'].", 'click', function() {
InfoWin".$deal['id'].".open(map,marker".$deal['id'].");
});
markers_1.push(marker".$deal['id'].");";
echo $t;
}
?>
var markerCluster_1 = new MarkerClusterer(map, markers_1, {maxZoom: 7, gridSize: 25, styles: styles[0]} );

Try to reduce your html code:
You should pass data to javascript as a json object. Than javascript should iterate over all elements and create markers , etc.. mutch sorter html code, and faster load.
I assume you use jQuery for javascript coding:
... //your code before the while loop
<?
$deals = array();
while($deal=mysql_fetch_assoc($query)){
$deals[$deal[$id]] = $deal;
}?>
<script type="text/javascript">
var deals = <?=json_encode($deals)?>;
var infoWindow = [];
var marker =[];
$.each(deals,function(k,v){
var i = k;
infoWindow[i] = new google.maps.InfoWindow({
content: v.info,
maxWidth: 300 });
markers[i] = new google.maps.Marker({
position: new google.maps.LatLng(v.lat, v.lng), icon: v.icon
});
google.maps.event.addListener(markers[i] , 'click', function(){
infoWindow[i].open(map,markers[i]);
});
});
var markerCluster_1 = new MarkerClusterer(map, markers, {maxZoom: 7, gridSize: 25, styles: styles[0]} );
</script>
And if it is not enough, you can load the data via ajax.

Related

Google Maps in Modal not centered

I'm using a Google Map in a modal. But it the center is not what I want.
I use following script:
<script>
function initMap() {
var lattp = <?php echo json_encode($lattp);?>;
var lngtp = <?php echo json_encode($lngtp);?>;
var zoomtp = <?php echo json_encode($zoomtp);?>;
var tp = {lat: JSON.parse(lattp), lng: JSON.parse(lngtp)};
var latrest = <?php echo json_encode($latrest);?>;
var lngrest = <?php echo json_encode($lngrest);?>;
var rest = {lat: JSON.parse(latrest), lng: JSON.parse(lngrest)};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: JSON.parse(zoomtp),
center: tp
});
var marker = new google.maps.Marker({
position: rest,
map: map
});}
$('#myModal').on('shown.bs.modal', function() {
google.maps.event.trigger(map, "resize");
map.setCenter(tp);
});
</script>
The result is not what I want. You can check it: https://www.checkjevoeding.be/uitstap/tp_rest_dishes.php?id=9
Just click on "Aanduiding parkplan"
You should move the map and tp out of the initMap() method as it is not accessible outside the method.
<script>
var map, tp;
function initMap() {
var lattp = <?php echo json_encode($lattp);?>;
var lngtp = <?php echo json_encode($lngtp);?>;
var zoomtp = <?php echo json_encode($zoomtp);?>;
tp = {lat: JSON.parse(lattp), lng: JSON.parse(lngtp)};
var latrest = <?php echo json_encode($latrest);?>;
var lngrest = <?php echo json_encode($lngrest);?>;
var rest = {lat: JSON.parse(latrest), lng: JSON.parse(lngrest)};
map = new google.maps.Map(document.getElementById('map'), {
zoom: JSON.parse(zoomtp),
center: tp
});
var marker = new google.maps.Marker({
position: rest,
map: map
});
}
$('#myModal').on('shown.bs.modal', function() {
google.maps.event.trigger(map, "resize");
map.setCenter(tp);
});
</script>

Google maps clear all markers before placing new one

I'm trying to place a marker on click in google maps along with populating input boxes with the lat and lng. I need the code to clear all the existing markers first before placing the new marker and updating the lat and lng. everything works except when I add code to try clear all the markers.
The below code works perfectly but does not clear the old markers before placing the new one.
Thank you.
Working code without clearing existing markers...
<div id="map"></div>
<script>
var map;
function initMap() {
var latlng = new google.maps.LatLng(-29, 25);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: latlng,
});
google.maps.event.addListener(map, 'click', function(event){
var marker_position = event.latLng;
marker = new google.maps.Marker({
map: map,
draggable: false
});
marker.setPosition(marker_position);
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
})
}
</script>
Not working code with clearing markers before adding a new one...
<div id="map"></div>
<script>
var map;
var markersArray = [];
function initMap() {
var latlng = new google.maps.LatLng(-29, 25);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: latlng,
});
markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(event){});
google.maps.event.addListener(map, 'click', function(event){
var marker_position = event.latLng;
marker = new google.maps.Marker({
map: map,
draggable: false
});
clearOverlays();
marker.setPosition(marker_position);
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
})
}
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
}
Thank you.
seem you have placed the code in the wrong place .. try
<div id="map"></div>
<script>
var map;
var markersArray = [];
function initMap() {
var latlng = new google.maps.LatLng(-29, 25);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: latlng,
});
clearOverlays();
marker = new google.maps.Marker({
map: map,
draggable: false
});
google.maps.event.addListener(marker,"click",function(event){});
google.maps.event.addListener(map, 'click', function(event){
var marker_position = event.latLng;
marker.setPosition(marker_position);
markersArray.push(marker);
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
})
}
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray = [];
}
</script>

Mark multiple locations on google map with google map api

I want to add multiple locations on google map. I have saved the longtitude and latitude in the database. Then I retrieve it from PHP and append the the data to a Javascript function. When I hardcode the locations in Javascript, it works fine. But when I load the data with PHP it's not working. But when I check it with Firebug, it shows that the PHP values have come to the relevant places. The issue is that nothing is loading. The following is the code I up with.
<script type="text/javascript">
function initialize() {
<?php
$con=mysqli_connect("HOST","DBUSERNAME","DBPASSWORD","TABLE");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM locations");
?>
var count=0;
var my = new google.maps.LatLng(7.860661,80.674896);
var mapOptions = {
zoom: 8,
center: my
}
<?php while($row = mysqli_fetch_array($result))
{
?>
var myLatlng;
var finallatlang=myLatlng.concat(count.toString());
finallatlang = new google.maps.LatLng(<?php echo $row['latitude'];?>,<?php echo $row['longtitude'];?>);
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: finallatlang,
map: map,
title: '<?php echo $row['location_name'];?>'
});
count++;
<?php } ?>
mysqli_close($con);
?>
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Updated my code
function initialize() {
$result = mysqli_query($con,"SELECT * FROM locations");
?>
//var count=0;
<?php $count=0;?>
var my = new google.maps.LatLng(7.860661,80.674896);
var mapOptions = {
zoom: 8,
center: my
}
<?php while($row = mysqli_fetch_array($result))
{
?><?php echo $count++;?>
//var myLatlng;
<?php $mylatlang="mylatlang";?>
//var finallatlang=myLatlng.concat(count.toString());
//var count=parseInt(<?php //echo $count;?>);
//var finallatlang=myLatlng+count.toString();
finallatlang = new google.maps.LatLng(parseFloat(<?php echo $row['latitude'];?>),parseFloat(<?php echo $row['longtitude'];?>));
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var latlang='<?php echo $mylatlang+$count?>';
//var latlang=Math.random();
var marker = new google.maps.Marker({
position: latlang,
map: map,
title: '<?php echo $row['location_name'];?>'
});
//count++;
}
google.maps.event.addDomListener(window, 'load', initialize);
This is the final answer which i was come up with.Special thanks to Rorschach.
<div id="map" style="width: 1000px; height: 900px;"></div>
<script type="text/javascript">
<?php
$con=mysqli_connect("HOST","HOSTUSERNAME","HOSTPASSWORD","DATABASE");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM locations");
?>
var locations = [<?php while($row = mysqli_fetch_array($result))
{?>
['<?php echo $row['location_name'];?>', <?php echo $row['latitude'];?>, <?php echo $row['longtitude'];?>],
<?php }?>
];
var latlng = new google.maps.LatLng(6.934947,79.862308);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
myOptions);
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})
(marker, i));
}
Your problem is here (info in your 'answer', not yet in your question):
new google.maps.LatLng('6.936992','79.860935')
The LatLng constructor expects two floating point numbers, not two strings. If it were
new google.maps.LatLng(6.936992,79.860935)
you'd be fine. Use parseFloat to convert these values to floats:
finallatlang = new google.maps.LatLng(
parseFloat(<?php echo $row['latitude'];?>),
parseFloat(<?php echo $row['longtitude'];?>)
);
Your db connection(php code):
<?php $con=mysql_connect("host","dbuser","dbpassword");
mysql_select_db("dbname",$con);
$result = mysql_query("SELECT * FROM locations");
?>
Google map multiple markers (Javascript code) :
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var locations = [
<?php while($row = mysql_fetch_array($result)) { ?>
['marker 1',<?php echo $row["lat"] ?>,<?php echo $row["longs"] ?>, 4],
<?php } ?>
];
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
myOptions);
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})
(marker, i));
}
</script>

Get latitude and longitude of multiple marker (onclick)

I have multiple markers in my map.
How to create a listener to multiple markers and get their latitude and longitude?
When I tried that event listener at one marker, it works. But when I tried that event listener with my multiple marker, it doesnt work.
Here is my code :
var jakarta = new google.maps.LatLng(-6.211544, 106.845172);
var shelterpoint = [];
var shelterName = [];
<?php while ($row = mysql_fetch_array($result)) { ?>
shelterpoint.push(new google.maps.LatLng(<?=$row['Latitude']?>, <?=$row['Longitude']?>));
shelterName.push("<?=$row['Shelter_Name']?>");
<?php } ?>
var markers = [];
var iterator = 0;
var map;
function initialize() {
var mapOptions = {
zoom: 12,
center: jakarta
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
drop();
google.maps.event.addListener(marker, "click", function (event) {
alert(this.position);
});
}
function drop() {
for (var i = 0; i < shelterpoint.length; i++) {
setTimeout(function() {
addMarker();
}, i * 10);
}
}
function addMarker() {
markers.push(new google.maps.Marker({
position: shelterpoint[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
title:shelterName[iterator]
}));
iterator++;
}
google.maps.event.addDomListener(window, 'load', initialize);
Please refer the link below.
http://jsfiddle.net/xJ26V/1/
var mapOptions = {
center: new google.maps.LatLng(-33.92, 151.25),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

Adding 2 google maps with different coordinates on same page

I have been working with a wordpress theme that has the support to just add coordinates in a menu and directly display the map on the contact page. Now I have a new business address that needs to be added to the contact map but the theme doesn't support that.
Giving the fact that my experience in php and js is limited I couldn't find a solution for my problem.
My code for the contact page is bellow and all I need is to add a new map with different coords before the contact form.
<div id="content">
<?php
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
$show_map = get_option('theme_gmap_show');
if($show_map == 'true')
{
$map_lati = get_option('theme_gmap_lati');
$map_longi = get_option('theme_gmap_longi');
$map_zoom = get_option('theme_gmap_zoom');
?>
<div class="map-container clearfix">
<div id="map_canvas"></div>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize()
{
var geocoder = new google.maps.Geocoder();
var map;
var latlng = new google.maps.LatLng(<?php echo $map_lati; ?>, <?php echo $map_longi; ?>);
var infowindow = new google.maps.InfoWindow();
var myOptions = {
zoom: <?php echo $map_zoom; ?>,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder.geocode( { 'location': latlng },
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
});
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
initialize();
</script>
</div>
<?php
}
the_content();
$postal_address = stripslashes(get_option('theme_postal_address'));
if(!empty($postal_address))
{
?>
<h3 class="smart-head">Adresa de contact</h3>
<p><address>
<?php echo $postal_address; ?>
</address></p>
<?php
}
?>
<div class="contact-orar">
<h3 class="smart-head">Program de Lucru</h3>
<p><strong>Luni - Vineri:</strong> 8:00 - 17:00<br />
<strong>Sambata:</strong> 8:00 - 14:00<br />
<strong>Duminica:</strong> inchis</p>
</div>
<div class="contact-form-container">
Thank in advance for any help!
You have to add a random key to the end of the call to your query. This is an example using KML layers, but it is the same concept.
$( function() {
$(".map_canvas").each( function() {
var theElement = $(this).attr('id');
var lat = $(this).attr('lat');
var lon = $(this).attr('lon');
var kml = $(this).attr('kml');
var mapCenter = new google.maps.LatLng(lat,lon);
var mapOptions = {
zoom: 14,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById(theElement), mapOptions);
var geopoints = new google.maps.KmlLayer('http://blah.com/temps/kmls/' + kml + '.kml?run=' + (new Date()).getTime() ); //?nocache=0
geopoints.setMap(map);
});
})
Even without any PHP knowledge you should be able to manage adding a map, the code uses the Google Maps API v3. You can easiliy add another map using JavaScript. First of all add another div with ID map_canvas_2 next you should use the following Javascript code:
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(/*latitude here*/,/*longitude here*/)
};
map = new google.maps.Map(document.getElementById('map_canvas_2'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
This will display a map centered on the coordinates you specify in the map_canvas_2 div. You can find more information here: https://google-developers.appspot.com/maps/documentation/javascript/reference
JsFiddle here: http://jsfiddle.net/Chycx/2/