I have google map embedded in a page with a Dropdown list containing a number of cities. I have stored the lat and lang values of those cities in a database. A user will select a city and the map will load with respective lat and lang values upon clicking the submit button. Please note that I don't want the geocoding technique. Here is a snippet of my effort.
var map;
var cntr;
var zm;
<?php
if(!empty($position['lat']) && !empty($position['lang'])){ ?>
var latValue = <?php $position['lat']; ?> ;
var langValue = <?php $position['lang']; ?> ;
cntr = {lat: latValue , lng: langValue };
zm = 8;
<?php} else{ ?>
cntr = {lat: 30, lng: 70};
zm = 7;
<?php } ?>
function initialize() {
var mapOptions = {
center: cntr,
zoom: zm
};
//And the rest of the code for markers and infowindows etc.
This doesn't work. It even stops the rest of the code to work which perfectly works when I remove this section and assign the default values to the var cntr.
(I am using MVC organization and the $position is an associative arrray of the cities lat and lang in the controller. The query works perfectly.)
You can't use php inside a .js file by default.You have to change your .htaccess accordingly.
Here is a site from a fast google search on how to do it. https://css-tricks.com/snippets/htaccess/use-php-inside-javascript/
cntr = {lat: latValue , lang: langValue };
That should say lng not lang.
I'm not sure how that would have been reported in the console; it would probably throw an error deep in the API code.
if(!empty($position['lat'] && !empty($position['lang'])))
shouldn't this be:
if(!empty($position['lat']) && !empty($position['lang']))
?
You have two errors in the code you have provided. First, you have to say
<?php echo $position['lat']; ?>
not
<?php $position['lat']; ?>
Second, instead of taking the default values for lat and lng inside the php loop, initialize the variables at the time you declare them. So the code you need will look something like:
var map;
var cntr = {lat: 30, lng: 70};
var zm = 7;
<?php if(!empty($position['lat']) && !empty($position['lang'])){ ?>
var latValue = <?php echo $position['lat']; ?> ;
var langValue = <?php echo $position['lang']; ?> ;
cntr = {lat: latValue, lng: langValue};
zm = 8;
<?php } ?>
function initialize() {
var mapOptions = {
center: cntr,
zoom: zm
};
//rest of the code
Hope this helps you.
Related
I have this code:
<?php $result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$result[] = sprintf("{lat: %s, lng: %s}",$row['lat'],$row['lng']);} ?>
<?php $resultAM = join(', ',$result);
echo $resultAM; ?>
the $resultAM represents this result (anyway I'm using SQL):
{lat: -7.0476101, lng: 112.7323577}, {lat: -7.0319093, lng: 112.7614287}, {lat: -7.0433001, lng: 112.7606889}, {lat: -7.0459718, lng: 112.7583679}
I'm going to put the code in javascript with this code:
var distanceM = [<?php echo json_encode($resultAM); ?>];
but the result wont appear.
Anyone can help me? I'm new at PHP. Thanks!
PHP 2D Array can simply transform into JS Array of objects. For example, we have a php array:
$arr = array('city1' => array('TBILISI' => 'Georgia'), 'city2' => array('LONDON' => 'UK'));
In JS we can simply write:
let myArr = <?php echo json_encode($arr); ?>;
console.log(myArr); // Console it..
it now looks in JS like that:
{"city1":
{"TBILISI": "Georgia"},
"city2":
{"LONDON": "UK"}
}
I just placed a google map on my website following the instructions from google maps API: https://developers.google.com/maps/documentation/javascript/adding-a-google-map
Copying that example works perfectly but I would like to get the position of the marker depending on a custom field created in each post from WordPress
<div id="map"></div>
<?php $lati = get_field( "gmapslat" ); ?>
<?php $lat = get_field( "gmapslng" ); ?>
<script>
function initMap() {
var lat = '<?php echo $lat; ?>';
var lng = '<?php echo $lng; ?>';
var uluru = {lat: lat, lng: lng};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
<script async defer
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDPGx6I2w6hzEmQNR2IrRKlFC9oUT-COvs&callback=initMap">
</script>
</div>
When do that the map just shows grey.
It seems there's a problem with your PHP variables. This PHP Variable $lng is not declared. So you are setting an undeclared PHP variable in Javascript variable lng.
I also noticed these lines:
<?php $lati = get_field( "gmapslat" ); ?>
<?php $lat = get_field( "gmapslng" ); ?>
Is this variable $lat value a longitude? If so, use $lng instead. Using meaningful names for variables would be helpful. Variable names must define the exact explanation of its content, regardless of programming language. Checking this blog 15 Best Practices of Variable & Method Naming might help.
Important: Use parseFloat() on each javascript variable width coordinates to return a floating point number. Else, it won't work and you'll just see a grey map. To learn more about definition and usage of parseFloat(), you can check JavaScript parseFloat() Function.
Below is a sample code using "-25.363, 131.044" as a sample coordinates returned by your PHP get_field() function:
<div id="map"></div>
<?php
function get_field($args) {
switch ($args) {
case 'gmapslat':
return '-25.363';
break;
case 'gmapslng':
return '131.044';
break;
}
}
$lat = get_field('gmapslat');
$lng = get_field('gmapslng');
?>
<script>
function initMap() {
var lat = parseFloat("<?php echo $lat; ?>");
var lng = parseFloat("<?php echo $lng; ?>");
var myLatLng = {lat: lat , lng: lng};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
Hope it could help and happy coding!
i have try to fetch lat and long value from mysql db and pass those value on google map for show location marker on map
but currently i have fetch only last rows data so indicate marker only one place
how to display all location on map??
<?php
include "config.php";
$result="select * from ds_duty_history";
$a=mysqli_query($conn,$result);
// $count_row = mysqli_num_rows($a);
while ($b = mysqli_fetch_array($a)) {
$long_d=$b['lng'];
$lat_d=$b['lat'];
$result = array(array('latitude'=>$lat_d,'longitude'=>$long_d));
}
?>
<!doctype html>
<html>
<head>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&callback=initMap">
</script>
<script type="text/javascript">
var map;
function initialize() {
// Set static latitude, longitude value
var latlng = new google.maps.LatLng(<?php echo $lat_d; ?>, <?php echo $long_d; ?>);
// Set map options
var myOptions = {
zoom: 16,
center: latlng,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Create map object with options
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
// uncomment the 2 lines below to get real data from the db
// $result = mysql_query("SELECT * FROM parkings");
// while ($row = mysql_fetch_array($result))
foreach($result as $row){ // <- remove this line
echo "addMarker(new google.maps.LatLng(".$row['latitude'].", ".$row['longitude']."), map);";}
?>
}
function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true, // enables drag & drop
animation: google.maps.Animation.DROP
});
return marker;
}
</script>
</head>
<body onload="initialize()">
<div style="float:left; position:relative; width:550px; border:0px #000 solid;">
<div id="map_canvas" style="width:550px;height:400px;border:solid black 1px;"></div>
</div>
</body>
</html>
currently display only one marker i.e last fetch record lat and long assign on map
how to display all place on map using mysql lat,long value?
The main problem you have here is that you're not actually collecting different results in your $result variable but overwrite it with the most recent one. The also seems to be some abuse of the variable $result which might be contributing to your confusion. Let's say we declare a new array and call it $rows. Then we can collect all the rows with the following code (to substitute your first snippet):
<?php
include "config.php";
$sql = "SELECT * FROM ds_duty_history";
$result = mysqli_query($conn, $sql);
$rows = [];
while ($row = mysqli_fetch_array($result)) {
$lon_d = $row['lng'];
$lat_d = $row['lat'];
// Use short-cut append syntax here so we add row and don't overwrite $rows
$rows[] = ['latitude' => $lat_d, 'longitude' => $long_d];
}
?>
Now in your display code (the second snippet) you would be able to iterate over $rows pretty much like:
foreach ($rows as $row){
// Do work with each $row here
}
Just as an aside, try to get used to using variable names that are as meaningful as possible and use new variables as much as you can. Trying to use short, generic variable names like $a will always lead to confusion since you won't know what it represents unless you find where you declared it every time. Trying to re-use a variable (like you did with $result) can make your life much more difficult since now even if you find an assignment to the variable, it is assigned many different times and (the way you used it) represents completely different types each time. Doing this one thing makes it just a little easier to get the hang of programming since at the very least you'll be able to read and make sense of your own intent when reading your own code.
Please try this code for display multiple marker on map
<script type="text/javascript">
var LocationData = <?php echo json_encode($result); ?>;
function initialize()
{
var myOptions = {zoom:12,mapTypeId: google.maps.MapTypeId.ROAD};
var map =
new google.maps.Map(document.getElementById('map-canvas'), myOptions);
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (var i in LocationData)
{
var p = LocationData[i];
var latlng = new google.maps.LatLng(p[0], p[1]);
bounds.extend(latlng);
var icon = { url: '<?php echo base_url();?>assets/frontend/assets/images/location_pin1.png', // url
scaledSize: new google.maps.Size(40, 70), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
var marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: true, // enables drag & drop
animation: google.maps.Animation.DROP
icon: icon
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I have a google map link that looks like this:
https://www.google.com/maps/place/Space+Needle/#47.620506,-122.349277,17z/data=!4m6!1m3!3m2!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d!2sSpace+Needle!3m1!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d
How can I extract coordinates from it in PHP or Javascript to get an array:
{47.620506, -122.349277}
If you're not using the api (Which isn't advisable), you could just put the page into a string, and extract the long/lat from within ... It's given multiple times on the page as the parameter ll ... I'm not very good with regex, so I'll give an example using strstr
<?php
$url='https://www.google.com/maps/place/Space+Needle/#47.620506,-122.349277,17z/data=!4m6!1m3!3m2!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d!2sSpace+Needle!3m1!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d';
$result=file_get_contents($url);
$ll=explode(',',substr(strstr(strstr($result,'?ll='),'&',true),4));
$long=$ll[0];
$lat=$ll[1];
?>
This is the code I am using on my web page at the moment. It is fairly easy to do as well.
<div id="map-canvas">
<script>
function initialize() {
var myLatlng;
var mapOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
//User Location
/* This is the cords */ myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
//So if you want them individually just use position.coords.l...
//Please feel free to ask questions
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</div>
If you use php it is quite easy to query the maps api with just about any address that Google will recognize:
$address = 'Space+Needle';
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response);
$ltlg = array($result->results[0]->geometry->location->lat, $result->results[0]->geometry->location->lng);
Hope this helps
Try this:
public function getCoordinatesAttribute() {
$url = "https://www.google.com/maps/place/Space+Needle/#47.620506,-122.349277,17z/data=!4m6!1m3!3m2!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d!2sSpace+Needle!3m1!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d";
$url_coordinates_position = strpos($url, '#')+1;
$coordinates = [];
if ($url_coordinates_position != false) {
$coordinates_string = substr($url, $url_coordinates_position);
$coordinates_array = explode(',', $coordinates_string);
if (count($coordinates_array) >= 2) {
$longitude = $coordinates_array[0];
$latitude = $coordinates_array[1];
$coordinates = [
"longitude" => $longitude,
"latitude" => $latitude
];
}
return $coordinates;
}
return $coordinates;
}
In my case, I have to make sure that the link is a google map location URL as it all depends on
the character "#" in the url.
i am using a php while loop to create a div class multiple times
so every time i have different lat lng
also in every loop i initialize a new map on a different div to create the map
and here is my code
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var title= "Title";
var lat = <?php echo $lat; ?>;
var lng = <?php echo $lng; ?>;
var myLatlng = new google.maps.LatLng(lat,lng);
var mapOptions = {
zoom: 14,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('beezMapBig<?php echo $tmp;?>'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
}
</script>
everytime the load works with the different lat,lng but i dont have the map 100% loaded
(i cant post image due to low reputation...imagine that the map is loading like 50% with the rest grey blank)
now the weird part is that when i press f12 at any browser to run the console to see some problems/failures the map is getting 100% loaded and resized.
Any ideas why this occurs and why the code is running correctly when run the browser console??
Thanks in advance!!
Had same issue and solved by doing this.
write ready() function. and then place the window resize functions in the initialize method itself (before initializing the map). It will help.
I can use PHP and JS. I have array with 3 elements.
Firstly Im generating div with unique id
<?php $i=0; foreach ($array as $single) : $i++; ?>
<div id="map_<?php echo $i; ?>" style="width: 100%; height: 300px;"></div>
<?php endforeach; ?>
Then im opening script tag like this
<script>
var maps = [];
<?php $i = 0; foreach($array as $single): $i++; ?>
maps.push({
mapContainer: 'map_'+<?php echo $i; ?>,
lat: <?php echo $single['mapa_google']['lat']; ?>,
lng: <?php echo $single['mapa_google']['lng']; ?>,
});
<?php endforeach; ?>
function initMap() {
for(var i = 0; i < maps.length; i++)
{
// The location of Uluru
var uluru = {lat: maps[i].lat, lng: maps[i].lng};
// The map, centered at Uluru
var map = new google.maps.Map(
document.getElementById(maps[i].mapContainer), {zoom: 16, center: uluru}
);
// The marker, positioned at Uluru
var marker = new google.maps.Marker({position: uluru, map: map});
}
}
</script>
On the bottom on my page im using async script
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&callback=initMap">
</script>
Of course in my array I have data for 3 google maps.