Google maps dynamic center point PHP - javascript

I'm trying to find out a way which i can have a dynamic center point, rather than have it static, Is there a way i can do this via the bounds method ?
For now i am getting the dynamic location but when the map loads, it is showing the static location, This new google.maps.LatLng(37.775196, -122.419204);
Which i want to point my dynamic location when the map loads.
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<?php
$res = $con->query("SELECT mrk_lat , mrk_lng FROM `marker_info` ORDER BY mrk_id DESC
LIMIT 1 ");
$mrk_cnt = 0;
while ($obj = $res->fetch_object()){
$lat[$mrk_cnt] = $obj->mrk_lat; // save the lattitude
$lng[$mrk_cnt] = $obj->mrk_lng; // save the longitude
$mrk_cnt++; // increment the marker counter
}
$res->close();
?>
<script type='text/javascript'>
var point;
var mrktx;
function load() {
addTo = 0;
var latlng = new google.maps.LatLng(37.775196, -122.419204);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
<?php
for ($lcnt = 0; $lcnt < $mrk_cnt; $lcnt++){
echo "var point$lcnt = new google.maps.LatLng($lat[$lcnt], $lng[$lcnt]);\n";
echo "var marker$lcnt = new google.maps.Marker({position: point$lcnt, map: map});\n";
}
?>
}
</script>
</head>
<body onload='load()'>
<div id="map_canvas" style="width: 1440px; height: 669px; margin: 0 0 0 0;"></div>
</div>

Just put your PHP variables containing the location using the echo shorthand:
new google.maps.LatLng(<?=$lat[$mrk_cnt]?>, <?=$lng[$mrk_cnt]?>)
Or in your code at the end:
echo "var point$lcnt = new google.maps.LatLng(" . $lat[$lcnt] . "," . $lng[$lcnt] . ");\n";

Related

insert multiple markers on google map

I wrote the code below... this code is to select to long and lati already inserted in database and create a marker in the google map, I tried to put the selected data in a table, it worked fine, but once I put them on the map as marker, it show me only on marker, can anyone help please?
<?php
$conn = getConn();
$sql ="select Latitude,Longtitude from location";
$result=$conn->query($sql);
while($row = mysqli_fetch_array($result)){
$locations = array(
$row['Latitude'],
$row['Longtitude']
);
foreach ($locations as $loc){
// echo $loc . "</br>";
$Latitude = $row['Latitude'];
$Longtitude = $row['Longtitude'];
echo $Latitude . "</br>" . $Longtitude;
}
}
?>
<script>
function initMap(){
var location = {lat: <?=$Latitude?>, lng: <?=$Longtitude?>};
var map= new google.maps.Map(document.getElementById("map"),{
zoom: 13,
center: location});
var marker = new google.maps.Marker({position:location, map:map});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyByZSFwCa5FByzySCLUPzLqzeWKt3RyNwA&callback=initMap">
</script>
You'll need to create an instance of marker for every one you want to appear on the map.
The location variable only holds the last one; you'll have to do something like:
var location = {lat: <?=$Latitude?>, lng: <?=$Longtitude?>};
var map = new google.maps.Map(document.getElementById("map"),{
zoom: 13,
center: location});
for (let loc of <?=$locations?>) {
new google.maps.Marker({position:loc, map:map});
}

How to show multiple Location on google map using php and mysql database

I have the following code, it works fine but picks only one location,
I have multiple location against 'cid' and I want to get and display all the location.
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<?php
$sql = "select * from locator_areas where cid=$city";
$res = mysql_query($sql);
while($row=mysql_fetch_assoc($res)){
?>
<script> var myLatLng = {lat: <?php echo $row['latitude'] ?>, lng: <?php echo $row['longitude']?>};</script>
<?php } ?>
<script>
function initMap() {
icon='img/bk-loc.png';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon:icon,
title: "<?php echo $long.' || '. $lat?> "
});
}
</script>
<script async defer
src="http://maps.googleapis.com/maps/api/js?key=myKEY&callback=initMap">
</script>
<script> initMap();</script>
</body>
You can add multiple markers by adding new google.Maps.Marker() multiple times. It would make sense to iterate over a array to do this.
The code should look like this
<?php
require("phpsqlsearch_dbinfo.php");
// Get parameters from URL
$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius = $_GET["radius"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
/ Opens a connection to a mySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Search the rows in the markers table
$query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
mysql_real_escape_string($center_lat),
mysql_real_escape_string($center_lng),
mysql_real_escape_string($center_lat),
mysql_real_escape_string($radius));
$result = mysql_query($query);
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
?>
Check out these links https://developers.google.com/maps/articles/phpsqlsearch_v3
https://developers.google.com/maps/articles/phpsqlajax_v3
You can add multiple markers by adding multiple times using for loop. It would make sense to iterate over a array to do this.
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<?php
$sql = "select * from locator_areas where cid=$city";
$res = mysql_query($sql);
while($row=mysql_fetch_assoc($res)){
$i=0;
?>
<script> var myLatLng = new Array();
myLatLng[<?php echo $i; ?>] = "<?php echo $value['latitude']; ?> , <?php echo $value['longitude']; ?>"; </script>
<?php
$i++;
} ?>
<script>
var locations = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < pins.length; i++) {
var coordinates = pins[i].split(", ");
locations[i] = new google.maps.LatLng(coordinates[0], coordinates[1]);
latlngbounds.extend(locations[i]);
}
var mapOptions = {
zoom: 9,
disableDefaultUI: true,
center: myLatlng,
draggable: false,
scrollwheel: false,
disableDoubleClickZoom: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
//var contentString = "<p>I am HTML</p>";
var image = 'img/bk-loc.png';
var markers = [];
for (var i = 0; i < locations.length; i++){
markers[i] = new google.maps.Marker({
position: locations[i],
map: map,
title: pin_quick_data[i],
icon: image
});
}
</script>
<script async defer
src="http://maps.googleapis.com/maps/api/js?key=myKEY&callback=initMap">
</script>
<script> initMap();</script>
</body>
You are saving N positions in one variable. In that variable only the last position is saved. If you want to save N positions in memory you have to use an array.
To ship PHP variables to Javascript I recomend to use PHP and the PHP function json_encode.
In the end of your example, you are calling initMap. It is not needed since this function is called from your googleapis script include.
Rewritten code should look like this:
<body>
<div id="map"></div>
<?php
$sql = "select * from locator_areas where cid=$city";
$res = mysql_query($sql);
$positions = array();
while($row=mysql_fetch_assoc($res)){
/* <script> var myLatLng = {lat: <?php echo $row['latitude'] ?>, lng: <?php echo $row['longitude']?>};</script>*/
$positions[] = array(
'lat' => $row['latitude'],
'lng' => $row['longitude'],
'title' => $row['longitude']. ' || ' .$row['latitude']
);
}
?>
<script>
var positions = <?php echo json_encode($positions) ?>;
</script>
<script>
function initMap() {
icon='img/bk-loc.png';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
positions.forEach(function(position){
var marker = new google.maps.Marker({
position: {
'lat' : position.lat,
'lng' : position.lng
},
map: map,
icon:icon,
title: position.title
});
});
}
</script>
<script async defer src="http://maps.googleapis.com/maps/api/js?key=myKEY&callback=initMap">
</script>
</body>

Referencing a particular location in google maps

I am trying to include google maps on a homepage for the first time and just found the code which creates a google map with a particular location -
var myLatlng1 = new google.maps.LatLng(53.65914, 0.072050)
and I don't know how to change the location where the marker is- where can I find the location coordinates? Thanks!
<html>
<head>
<title> Map </title>
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 500px;
width: 800px;}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false">
</script>
<script>
var map;
function initialize()
{
var myLatlng1 = new google.maps.LatLng(53.65914, 0.072050);
var mapOptions =
{
zoom: 10,
center: myLatlng1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
<?php
$sql = mysql_query("SELECT * FROM data ORDER BY ID DESC");
while($row =mysql_fetch_array($sql))
{
$desc = $row['DESCRIPTION'];
$location = $row['LOCATION'];
$counter += 1;
?>
var marker = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $location; ?>),
map: map,
title: '<?php echo $desc; ?>',
icon: '/image/cam.png'
});
navigator.geolocation.getCurrentPosition(showPosition);
}
var showPosition = function (position)
{
map.setCenter(new google.maps.LatLng(position.coords.latitude,
position.coords.longitude), 16);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
This is easy . First go to google maps and select the location you want to zoom in on. Once there look at the url at the top of the page it should look like this:
https://www.google.com/maps/#44.0005355,-71.0799974,12z
This is your lat long 44.0005355 and -71.0799974 Just replace them with the ones you have.
The portion of code that set the marker ( included the position) is this
var yourLat = 45.2323; // is only sample value
ver yourLng = 14.1818; // is only sample value
var marker = new google.maps.Marker({
position: new google.maps.LatLng(yourLat, yourLng),
map: map,
title: 'your title',
icon: '/image/cam.png'
});
You must assign the coord in google map notation so if you haven't this coord use google maps and click the point you desise. the coord appear in a box

google map markers php

I am able to display my mp ok, but when I go to add markers it is no longer loading the map... i.e. when I add the latter php code to my initialize function it doesn't work! Any ideas??!
<script type="text/javascript">
var map = null;
function addMarker(lat, lng){
var point = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: point,
map: map
});
}
function initialize() {
var mapOptions = {
center: {lat: 54.872128, lng: -6.284874},
zoom: 15
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
<?php
$query = mysqli_query("select * from tester") or die(mysqli_error());
while($row = mysqli_fetch_array($query)){
$lat = $row['lat'];
$lng = $row['lng'];
echo ("addMarker($lat, $lng);");
?>
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas" style="height:600px; width:600px;
margin-top:100px; margin-bottom: 100px;
">
</div>
You have an issue with the scope of map, in your initialize function you are redeclaring it inside that scope instead of populating the previous map var, remove the var from your function as follows:
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); //Note i've removed the "var" keyword from this line.
A little more explanation:
var map = null; -> declared in global scope.
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); -> declared inside initialize function scope.
var marker = new google.maps.Marker({
position: point,
map: map // -> NULL because it will look for map in the parent scope.
});
I've found the issue, you are missing the closing bracers of your while statement:
<?php
$query = mysqli_query("select * from tester") or die(mysqli_error());
while ($row = mysqli_fetch_array($query)) {
$lat = $row['lat'];
$lng = $row['lng'];
echo ("addMarker($lat, $lng);");
} //Missing!!!
?>

fetch multiple latitude and longitude from database and display their marker on google map

i have a code that is supposed to fetch data (latitude and longitude) from database and display it on google map along with markers, the problem is that it fetches and displays latitude and longitude of only one row, but it is supposed to show all the places. Would appreciate if anyone could help me.
<script>
<?php
require 'connection.php';
$parent_id = $_GET['country'];
$fid = $_GET['fid'];
$sql = "SELECT * FROM features_for_office WHERE parent_id='".$parent_id."' and fid='".$fid."' ";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$officeid= $row["officeid"];
$sql1 = "SELECT * FROM register_office WHERE id='".$officeid."' ";
$result1 = mysqli_query($con, $sql1);
if (mysqli_num_rows($result1) > 0)
{
while($row1 = mysqli_fetch_assoc($result1))
{
$officelat= $row1["lat"];
$officelon= $row1["lon"];
$officetitle= $row1["officetitle"];
//echo $officelat;
//echo $officelon;
//echo $officetitle;
?>
var myCenter=new google.maps.LatLng(<?php echo $officelat;?>,<?php echo $officelon;?>);
function initialize()
{
var mapProp = {
center:myCenter,
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content:"<?php echo $officetitle;?>"
});
infowindow.open(map,marker);}
google.maps.event.addDomListener(window, 'load', initialize);
<?}
}
}
}
mysqli_close($con);
?>
</script>
<div id="googleMap" style="width:1145px;height:380px;"></div>
The error is that you are initializing the map every time until the loop completes,it will recreate the map every time and the last latlon marker will be shown on the map.Call the initialize method on page load and place the following code inside the loop.
var myCenter=new google.maps.LatLng(<?php echo $officelat;?>,<?php echo $officelon;?>);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
using SQL you can fetch Latitude and Longitude from Database using this code:
protected void googleMap_Load(object sender, EventArgs e)
{
//Establishing SQL connection
SqlConnection connStr = new
SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
connStr.Open();//Open the connection to Database
//Generate the database query to fetch the content details
SqlCommand cmd = new SqlCommand("select LAT,LON from DATA where ID=9", connStr);
SqlDataAdapter sqlda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sqlda.Fill(ds);
}
The Problem still remains as how to use this dataTable to set marker on google map...
The problem can be re-framed as to fetch the LatLng from database
I used the script to display map
<script>
var myLatLon = new google.maps.LatLng(13, 77);//Defining Latitude and Longitude
var mapProp = {
center: myLatLon, // Center of display page.
zoom: 8, //Zoom level
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('dvMap'), mapProp);
var marker = new google.maps.Marker({
position: myLatLon,
map: map,
});
</script>

Categories

Resources