Adding 2 google maps with different coordinates on same page - html

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/

Related

how to display address over each marker in google map

My code is displaying markers on every output location but i want to display address over marker.I mean when user click the marker the address will have to appear above marker.How i can achieve this task? I have only latitude and longitude not address.
test.php:
<?php
$sql=<<<EOF
SELECT * from markers;
EOF;
$result = $db->query($sql);
$yourArray = array();
$index = 0;
while($row = $result->fetchArray(SQLITE3_ASSOC) ){
$json[] = array(
'lat' => $row['latitude'],
'lon' => $row['longitude'],
'name' => $row['name']
);
}
$db->close();
?>
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 50%;
}
</style>
</head>
<body>
<h3></h3>
<div id="map" align="left"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDj38Snh4MEIsomOlTZfARryo7V8A_qk9o&callback=initMap">
</script>
<?php json_encode($json, JSON_PRETTY_PRINT) ?>
<script type="text/javascript">
function initMap() {
var locationsJSON = <?php echo json_encode($json, JSON_PRETTY_PRINT) ?>;
var locations = locationsJSON;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(31.5546, 74.3572),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
for (i = 0; i < locations.length; i++) {
console.log(locations[i]);
var myLatLng = new google.maps.LatLng(locations[i].lat, locations[i].lon);
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
}
}
</script>
</body>
</html>
If all you have is the coordinates (latitude and longitude), your only option is to use the reverse geocoder:
(from that documentation):
The term geocoding generally refers to translating a human-readable address into a location on a map. The process of doing the converse, translating a location on the map into a human-readable address, is known as reverse geocoding.
However (unless the code you posted is not the area you are planning on mapping) the area of your map doesn't seem to produce reliable reverse geocode results. So I would suggest you populate the database with the address as well as the coordinates.
fiddle using reverse geocoded results in the infowindow
code snippet:
function initMap() {
var locationsJSON = [
{lat: 31.564614,lon: 74.298718},
{lat: 31.563892,lon: 74.300435},
{lat: 31.565546,lon: 74.297597},
{lat: 31.565332,lon: 74.296744},
{lat: 31.565332,lon: 74.296744},
{lat: 31.565272,lon: 74.297637},
{lat: 31.562347,lon: 74.296712}];
var locations = locationsJSON;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(31.5546, 74.3572),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
var myLatLng = new google.maps.LatLng(locations[i].lat, locations[i].lon);
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
google.maps.event.addListener(marker, 'click', function(evt) {
var mark = this;
geocoder.geocode({
location: evt.latLng
}, function(results, status) {
if (status == "OK") {
infowindow.setContent(results[0].formatted_address + "<br>" + results[0].geometry.location.toUrlValue(6));
infowindow.open(map, mark);
}
});
});
};
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Google Map not displaying - localhost

This exact code has worked on previous projects, however it is not working now.
The map does not display, however I see the JS show in chrome inspect tools. The div element for the map is there etc, just no visible map. I am using AFC, and have triple checked spelling etc.
Code below:
<!--place google map here-->
<div id="view1">
<?php
$location = get_field('store_location');
if( ! empty($location) ):
?>
<div id="map" style="width: 100%; height: 350px;"></div>
<script src='http://maps.googleapis.com/maps/api/js?sensor=false' type='text/javascript'></script>
<script type="text/javascript">
//<![CDATA[
function load() {
var lat = <?php echo $location['lat']; ?>;
var lng = <?php echo $location['lng']; ?>;
// coordinates to latLng
var latlng = new google.maps.LatLng(lat, lng);
// map Options
var myOptions = {
zoom: 9,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//draw a map
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
}
// call the function
load();
//]]>
</script>
<?php endif; ?>
</div>
See any problems?
Issue had to do with flexbox and bootstrap. Was using flexbox for equal column height throught site, but that seems to break this AFC google map. Placed the map outside the bootstrap column and issue was resolved.

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>

Multiple Google Maps on Same Page from Mysql?

I have a page that a user inputs markers on a google map and it saves the center of map latitude and longitude, zoom and the latitude and longitude of the marker into MySQL. Next I'm trying to have a page that displays all the different maps a user has saved with the markers. I have searched and all I can find is how to display multiple markers on the same map or a set number of maps on the same page with a set lat and long.
Could anybody suggest where to start with this or a tutorial on this.
Here is the code I've started with that displays one google map with all the markers that have been entered. Not familiar with javascript, so need pointed in the right direction.
Thanks
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=&sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
function load() {
var latitude= <?php echo json_encode($maplat);?>;
var longitude= <?php echo json_encode($maplon); ?>;
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(latitude, longitude),
zoom: <?php echo $mapzoom;?>,
mapTypeId: 'satellite'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var date = markers[i].getAttribute("date");
var log = markers[i].getAttribute("log");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latit")),
parseFloat(markers[i].getAttribute("longit")));
var html = "<b>" + date + "</b> <br/>" + log;
var marker = new google.maps.Marker({
map: map,
position: point,
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>

google map markers performance

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.