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>
Related
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>
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>
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
};
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/
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.