I'm new to php and I'm trying to display a google maps location with dynamic coordinates. Here's the code where I do the queries:
$longitudine="select longitudine from sedi, stati, tappe, spedizioni where $idSpedizione=tappe.spedizione and tappe.stato=idStato and sedi.citta=tappe.luogoInizio group by data desc limit 1;";
$longi=$conn->query($longitudine);
$longg=mysqli_fetch_array ($longi);
$latitudine="select latitudine from sedi, stati, tappe, spedizioni where $idSpedizione=tappe.spedizione and tappe.stato=idStato and sedi.citta=tappe.luogoInizio group by data desc limit 1;";
$lati=$conn->query($latitudine);
$lat=mysqli_fetch_array ($lati);
And here is the code:
<style>
#map {
height: 400px;
width: 100%;
}
</style>
<div id="map"></div>
<script>
function initMap() {
var uluru = { lat: 47.37, lng: 9.200000 };
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: uluru,
});
var marker = new google.maps.Marker({
position: uluru,
map: map,
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap&libraries=&v=weekly"
></script>
Basically I want to set the coordinates with the values of the queries, but when I try it doesn't show me the map. Can anyone help me?
If your both php and script code as above are on the same page, you can add php variables to your script's uluru variable as:
var uluru = { lat: <?php echo floatval($lat["latitudine"]) ?>, lng: <?php echo floatval($longg["longitudine"]) ?> };
Please note its not a standard way to add php variables to your script code like that but it may work on your code. You can try.
P.S: Please don't reveal your API key as you did in your question. Please edit and change it to MY_API_KEY or something in your question above.
Related
I have created an API that returns a json consisting of a latitude and longitude, and wanted to pass that into the Google Maps API, to get the corresponding map.
To get the data from my API I created an ajax request as follows:
scripts.js:
$(document).ready(function(){
$("button").click(function(){
$.get("my url", function(data, status){
//do something with this data
});
});
});
After I get the JSON from this, I want to pass the latitude and longitude to the script that Google Maps API provides as follows, inside my index.html.
index.html
<body>
<h1> JOS Map App </h1>
<button>Send an HTTP GET request to a page and get the result back</button>
<script type="text/javascript" src = "js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src = "js/scripts.js"></script>
<div id="map"></div>
<script> //THIS ONE!!
function initMap() {
var uluru = {lat: , lng: };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
Basically, I want to be able to pass the latitude and longitude from my GET request to this script so that I can pass them into the google maps API call. I am fairly new to jQuery, so have no idea how to do this.
Thanks!
Why not just pass the lat/lng as parameters to the Google Maps init()?
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("my url", function(data, status){
initMap(data.lat, data.lng);
});
});
});
function initMap(lat, lng) {
var uluru = {lat: lat, lng: lng};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
You can move that initMap() function to scripts.js. Just make sure you're loading Google Maps API before your scripts.js.
I want to specify location in google map, I have javascript codes work fine but I do know how I can specify location from php variable
Below are sample codes.
<html>
<head>
<title></title>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCqgya6hvq6zu3Z2xeT5xEGPPi5pY2ize4&callback=initMap"></script>
</head>
<body>
<?php
//I want to search this location in google map
$location="Kigali Rwanda";
?>
<script>
var myMap;
var myLatlng = new google.maps.LatLng(52.518903284520796,-1.450427753967233);
function initialize() {
var mapOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP ,
scrollwheel: false
}
myMap = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: myMap,
title: 'Name Of Business',
icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map" style="width:500px; height: 500px;">
</div>
</body>
</html>
Please anyone can help me
You can use Geocoding service in this case
function initMap() {
//var address = '<?php echo $location ?>';
var address = 'Kigali Rwanda';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
map.setCenter(results[0].geometry.location);
}
});
}
#map {
height: 400px;
width: 100%;
}
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
you have to use lat, lng to specifiy location. In case of country or state name you should get lat, lng of the location and define it in the code. insert the value of php variable in hidden input field. On running script get the value and process it.
I have problem coding the google maps API for my personal website. The google maps doesn't work until I refresh the browsers. Below are the scripts for google maps.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&v3"></script>
<script type="text/javascript" src="<?php echo get_bloginfo('template_url'); ?>/js/mk.js"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new MarkerWithLabel({
position: results[0].geometry.location,
map: map,
labelContent: address,
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 1.0}
});
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
initialize();
codeAddress("<?php
global $post;
$pid = $post->ID;
$terms = wp_get_post_terms($pid,'ad_location');
foreach($terms as $term)
{
echo $term->name." ";
}
$location = get_post_meta($pid, "Location", true);
echo $location;
?>");
</script>
Did I missed anything for the scripts? I didn't add API on it, but the console said "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."
You need to make sure the map variable is initialized before you pass it to markerOptions.
A bit of overzealous debugging showed me that on the times that the page fails, the map is still undefined.
The $(document).ready() will usually occur before body.onload, so either put a call to initialize() at the very top of your $(document).ready(function() { ... }); or put the code for initialize in there.
Also, though not strictly necessary, you should consider encapsulating your map variable instead of using a global.
I have looked to the solutions on stack exchange for this but not able to shape it up with my code. My code is :-
foreach($json_decode as $row){
$lat_d= $row->Latitude;
echo("\n");
$long_d= $row->Longitude;
}
error_log($lat_d);
error_log($long_d);
<html>
<head>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api
/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
var latlng = new google.maps.LatLng(<?php echo $lat_d; ?>, <?php echo $long_d; ?>);
var myOptions = {
zoom: 16,
center: latlng,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
echo "addMarker(new google.maps.LatLng(".$lat_d.", ".$long_d."), 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:1421px;height:700px;border:solid black 1px;"></div>
</div>
</body>
</html>
This code works only to show the single point on map. But can somebody help to tell me how the marker position can be changed depending on the changing latitude and longitude.
I am not able to separate the map with the contents .Everytime i try doing it using setInterval(), it reloads the entire map to me. I will be thankful if anybody can help me with this.
Please help me with this. I am stuck at this point.
I am using the WP Favorite Posts plugin to allow users to select their favourite tours on the site. The posts are saved using to cookies to a saved template provided by the plugin. I have edited this template to include a map and to pull the coordinates from a Custom Meta Field.
The full template can be found at http://pastebin.com/zDrr5fPn.
The code I have included to display the map is:
<div id="map" style="width: 100%; height: 250px; position: relative; overflow: hidden; -webkit-transform: translateZ(0px); background-color: rgb(229, 227, 223);"></div>
and the code I am using for the loop is:
while ( $loop->have_posts() ) : $loop->the_post();
if ( get_post_meta($post->ID, 'custom_latlng', true) !== '' ) : ?>
<div style="display:block;">
<script type="text/javascript">
function initialize() {
//load map
map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: new google.maps.LatLng(53.3498, -6.2603),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
});
var savedMarkers = new Array();
<?php $saved_pos = get_post_meta($post->ID, 'custom_latlng', true);?>
function addMarker() {
var savedMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(<?php echo $saved_pos ?>),
icon: '/wp-content/themes/dublin-visitors-centre/images/saved_icon.png',
});
savedMarkers.push(savedMarker);
}
}
</script>
</div>
At the moment, when I view the source, I can see the points being selected, the coordinates do appear. However they do not appear on the map itself. It is as if the points are appearing in the list of saved posts but not on the map at all.
I hope this makes sense.
Cheers
Inside the loop only populate an array with the latitudes/longitudes, create initialize outside of the loop:
<div id="map" style="width: 100%; height: 250px;"></div>
<script type="text/javascript">
function initialize() {
//load map
map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: new google.maps.LatLng(53.3498, -6.2603),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
});
//create the markers
for(var i=0;i<savedMarkers.length;++i){
savedMarkers[i] = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(savedMarkers[i][0],
savedMarkers[i][1]),
icon: '/wp-content/themes/dublin-visitors-centre/images/saved_icon.png',
});
}
}
<?php
//create a php-array to store the latitudes and longitudes
$savedMarkers=array();
//use the loop to populate the array
while ( $loop->have_posts() ) : $loop->the_post();
if ( get_post_meta($post->ID, 'custom_latlng', true) !== '' ) :
$savedMarkers[]=explode(',',get_post_meta($post->ID, 'custom_latlng', true));
endif;
endwhile;
?>
//print the array as js-variable
savedMarkers= <?php echo json_encode($savedMarkers);?>;
</script>
It's not tested, there may be some errors, but it should be sufficient to demonstrate the workflow.
Related to the comments:
To apply the post-title as infowindow-content also store the title in the savedMarkers-items:
$savedMarkers[]=array_merge(explode(',',get_post_meta($post->ID, 'custom_latlng', true)),
array(get_the_title()));
when you create the marker create a custom property for the marker where you store the infowindow-content(let's call the property content):
//create the markers
for(var i=0;i<savedMarkers.length;++i){
savedMarkers[i] = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(savedMarkers[i][0],
savedMarkers[i][1]),
icon: '/wp-content/themes/dublin-visitors-centre/images/saved_icon.png',
//the content(post-title)
content: savedMarkers[i][2]
});
}
Now use this content as infowindow-content:
google.maps.event.addListener(savedMarkers[i], 'click', function() {
infowindow.setContent(this.get('content'));
infowindow.open(this.getMap(), this);
}
);
You may also create a link to the posts inside the infowindows:
$savedMarkers[]=array_merge(explode(',',get_post_meta($post->ID, 'custom_latlng', true)),
array(get_the_title(),get_permalink()));
......
//create the markers
for(var i=0;i<savedMarkers.length;++i){
savedMarkers[i] = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(savedMarkers[i][0],
savedMarkers[i][1]),
icon: '/wp-content/themes/dublin-visitors-centre/images/saved_icon.png',
//the content(post-title)
title: '' + savedMarkers[i][2],
//post-URL
href: savedMarkers[i][3]
});
}
..........
google.maps.event.addListener(savedMarkers[i], 'click', function() {
var link=document.createElement('a');
link.appendChild(document.createTextNode(this.get('title')));
link.setAttribute('href',this.get('href'));
infowindow.setContent(link);
infowindow.open(this.getMap(), this);
}
);