Populating PHP inside Google Map script not working - php

I'm sure this is a simple issue, but I just can't seem to find the answer. I am trying to simply put google map on a site using dynamic lat & long from php call.
When I have this code it works:
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
function initialize() {
var bryantPark = new google.maps.LatLng(37.869260, -122.254811);
var panoramaOptions = {
position: bryantPark,
pov: {
heading: 165,
pitch: 0
},
zoom: 1
};
var myPano = new google.maps.StreetViewPanorama(
document.getElementById('map-canvas'),
panoramaOptions);
myPano.setVisible(true);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas"></div>
However, when I update it so that the LatLng is dynamic with php call like so:
<?php include("inc/conn.php"); ?>
....
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
function initialize() {
var bryantPark = new google.maps.LatLng(<?=$row["field_Latitude"]?>, <?=$row["field_Longitude"]?>);
var panoramaOptions = {
position: bryantPark,
pov: {
heading: 165,
pitch: 0
},
zoom: 1
};
var myPano = new google.maps.StreetViewPanorama(
document.getElementById('map-canvas'),
panoramaOptions);
myPano.setVisible(true);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas"></div>
When I view the source, I see that the lat & long are populating, but there is just a gray box where the street view should be.
Any thoughts?
Thanks!

When you want to show a map when streetView is not available(let's assume that streetview is not available when there is no panorama within a radius 50 meters), create a map and request the streetViewService to check if there is a panorama available for the given location.
When it does, set the position of the panorama and show it, otherwise do nothing.
function initialize() {
//center of the map and position of the panorama (when available)
var center = new google.maps.LatLng(42.698776, -86.181015),
//first initialize the map
map = new google.maps.Map(
document.getElementById('map-canvas'),
{
zoom:21,
center:center,
mapTypeId:google.maps.MapTypeId.SATELLITE
}
),
svService = new google.maps.StreetViewService(),
panoramaOptions = {
pov: {
heading: 165,
pitch: 0
},
zoom: 1,
visible:true
};
//test whether a panorama is available
svService.getPanoramaByLocation(center, 50, function(data,status){
if(status==google.maps.StreetViewStatus.OK){
//panorama is available, show it
var sv=map.getStreetView();
sv.setPosition(center);
sv.setOptions(panoramaOptions);
}
});
}
Demo: http://jsfiddle.net/doktormolle/7noptz5x/

First of all I will use <?php echo $row[...]; ?> instead of <?= $row[...] ?> , just to be sure that code works also if you have short tags disabled.
Secondly, I'd put:
<?php
$row = array(
'field_Latitude' => 37.869260,
'field_Longitude' => -122.254811
);
?>
instead of your include call and check the results to verify if I have something wrong in the included file.
In any case you should inspect the resulting HTML and check what are the real arguments passed to LatLong instead of the expected ones.

Related

“You have included the Google Maps API multiple times on this page” Error

I have seen this topic suggesting a solution to the issue i'm facing at the moment although not sure how to implement it since i'm using a code that is part of php system I recently purchased, not sure how to modify my code for it
This is how it runs on my code at the moment
array('file' => '', 'path' => 'https://maps.google.com/maps/api/js?'.$api_key_str.'sensor=false&language=' . $this->option_arr['o_map_language'])
How should I apply the code so I would be able to run google maps more than once in a page?
Thanks!
It seems that you are trying to implement the map more than once and you are calling the Maps Javascript API script tag. Please note that the Maps Javascript API script tag should only be called once and you can add multiple maps in your site by declaring multiple maps instantiation like:
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
Here is a sample as well:
var map;
var map1;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
map1 = new google.maps.Map(document.getElementById('map-1'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 45%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-1 {
height: 45%;
}
<h3>
Map #1
</h3>
<div id="map"></div>
<h3>
Map #2
</h3>
<div id="map-1"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAj0aaMu_aY6xiDSWH0ac_4pqN_l-opwmI&callback=initMap" async defer></script>
Hope this helps.

Google Map pop -up windows doesn't show anything inside it

i am using PHP MYSQL on WordPress with Google Map API where the code retrieve data from the MYSQL database and display markers on the map based on the existing coordinates in the database. also it display a infowindow on click Listener.
the problem is that the infow window doesn't shows any data inside of it.
can anyone one tel me where is the error?
code:
<?php
/*
Template Name: MAP2
*/
get_header();
?>
<!DOCTYPE html>
<html>
<head>
<title>Custom Markers</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=**********&callback=initMap">
</script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 600px;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map,currentPopup;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: new google.maps.LatLng(33.888630, 35.495480),
mapTypeId: 'roadmap'
});
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var icons = {
parking: {
icon: iconBase + 'parking_lot_maps.png'
},
library: {
icon: iconBase + 'library_maps.png'
},
info: {
icon: iconBase + 'info-i_maps.png'
}
};
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
//icon: icons[feature.type].icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: feature,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
var features = [
<?php
global $wpdb;
$prependStr ="";
foreach( $wpdb->get_results("SELECT siteID, latitude, longitude FROM site_coordinates2", OBJECT) as $key => $row) {
$latitude = $row->latitude;
$longitude = $row->longitude;
$info = $row->siteID;
echo $prependStr;
?>
{
position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
}
<?php
$prependStr =",";
}
?>
];
for (var i = 0, feature; feature = features[i]; i++) {
addMarker(feature);
}
}
</script>
</body>
</html>
<?php
get_footer();
?>
If I'm reading your code right, you've got an array of features that looks like:
features = [
{position: new google.maps.LatLng(1, 2)},
{position: new google.maps.LatLng(3, 4)},
// etc...
];
i.e. the array contains objects with just a position property. So you correctly refer to that when you do:
position: feature.position,
However when you try and set your infowindow content using:
new google.maps.InfoWindow({
content: feature,
maxWidth: 300
})
That won't work, because the content property is meant to be a string, not a JS object. You need to specify some text there. If you're just wanting to display the coordinates, you could do:
new google.maps.InfoWindow({
content: feature.position.toString(),
maxWidth: 300
})

Yii: Any extension to implement embedded google map

im a yiibie, and i want to use google maps in my project just like embedded google maps. For example i want that when an ngo(in my case) is registering there ngo they could give there address, type of map etc (just like in embedded google map) on the map so that people visiting that ngo page could easily locate that ngo and can get a route to that ngo, i have no idea of how and where using these google maps, please help me, thank you.
I don't know extension but you can easly create you map this way (in this sample there isn't the google maps key but if your app usage require this you should obtain one)
In Your <head> section add this
'<script src="https://maps.googleapis.com/maps/api/js?sensor=false&v=3&"></script>'
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
In <body> add
<body>
<div id="map" ></div>
<script>
var yourLat = <?= $yourLat; ?>
var yourLng = <?= $yourLng; ?>
function init() {
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(yourLat , yourLng)
}
var mapElement = document.getElementById('map');
// Create the Google Map using out element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
var myLatLng = new google.maps.LatLng(yourLat, yourLng);
var yourMarker = new google.maps.Marker({
position: myLatLng,
map: map,
});
}
// Google Maps Scripts
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
</script>
......
</body>

Marking route on Google map with multiple latitude and longitude values from database

I have written a PHP and javaScript code which will retrieve latitude and longitude informations from Database and place markers on Google map according in appropriate places(using lat and lon values). This works fine.
I need to join these markers and draw route on the map. How to do it.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<style type="text/css">
body { font: normal 10pt Helvetica, Arial; }
#map { width: 350px; height: 300px; border: 0px; padding: 0px; }
</style>
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info)
{
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker(
{
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow(
{
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function()
{
if (currentPopup != null)
{
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function()
{
map.panTo(center);
currentPopup = null;
});
}
function initMap()
{
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions:
{
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
}
});
$.getJSON('googlescript.php', function(items)
{
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.long, '<b>' + item.name + '</b><br />' + item.desc);
})(items[i]);
}
});
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</html>
Modify your JSON return function to something like this:
$.getJSON('googlescript.php', function(items)
{
var routePoints = [];
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.long, '<b>' + item.name + '</b><br />' + item.desc);
})(items[i]);
routePoints.push(new google.maps.LatLng(items[i].lat,items[i].long));
}
var route= new google.maps.Polyline({
path: routePoints,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
route.setMap(map);
});
I think you look for the Polyline object and you can see how to use within the google maps documentation
If you got a larger project I can advice using gmap2 using .kml files. But you should be able to accomplish your goal using the google documentation easily..
You will need to learn about the POLYLINE ARRAYS to accomplish connecting all the markers with a line. The documentation explains it very well.
However, the polyline arrays use javascript arrays, so if you are looking for fetching the lat lng values from a Database then you should look for some way to pass an array of the lat lng's fetched from database to the JavaScript function. There is already an article in the site that shows how to work Using PHP/MySQL with Google Maps . Look into the article and learn using polyline arrays and that should help you out.

Facing the targeted building with Google StreetView

My question is very straightforward.
I need the heading value to know how to target the POV.
sv.getPanoramaByLocation() in this case returns a data variable containing the heading of both the arrows in which direction you can go further.
However it doesn't give me the heading value for which way to look at the building. However it is possible to use a marker in streetview to target your building! example
Can anyone help me with this? I can make whatever dump you people want.
Geocode the address of the building you want to "look at". Use the geometry library
computeHeading(from:LatLng, to:LatLng) function to calculate the heading between the StreetView location and the building.
(assumes that the geocoder returns a "rooftop" geocode)
example (Statue of Liberty)
another option, use the directions service:
related question: Request main road StreetView panoramas instead of back alleys from API
code snippet that uses the directions service to get a location on the road to use for street view "camera" location (works better now that you can get "interior" streetview locations returned):
var map;
var berkeley = new google.maps.LatLng(37.869085, -122.254775);
var sv = new google.maps.StreetViewService();
var geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService();
var panorama;
var myLatLng;
var address = "525 Beacon St. Boston, MA";
function initialize() {
panorama = new google.maps.StreetViewPanorama(document.getElementById("pano"));
directionsService.route({
origin: address,
destination: address,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// myLatLng = response.routes[0].legs[0].start_location;
sv.getPanoramaByLocation(response.routes[0].legs[0].start_location, 50, processSVData);
var marker = new google.maps.Marker({
position: response.routes[0].legs[0].start_location,
map: map,
title: "Directions"
});
map.setCenter(myLatLng);
} else document.getElementById('info').innerHTML += "status:"+status+"<br>";
});
geocoder.geocode({
'address': address
}, geocoderCallback);
// Set up the map
var myOptions = {
zoom: 15
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
function processSVData(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
panorama.setPano(data.location.pano);
var camera = new google.maps.Marker({
position: data.location.latLng,
map: map,
draggable: true,
title: "camera"
});
var heading = google.maps.geometry.spherical.computeHeading(data.location.latLng, myLatLng);
document.getElementById('info').innerHTML += "heading:"+heading+"<br>"
+ "location: "+myLatLng.toUrlValue(6)+"<br>"
+ "camera:"+data.location.latLng.toUrlValue(6)+"<br>";
// alert(data.location.latLng+":"+myLatLng+":"+heading);
panorama.setPov({
heading: heading,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
} else {
alert("Street View data not found for this location.");
}
}
function geocoderCallback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
myLatLng = results[0].geometry.location;
map.setCenter(myLatLng);
if (results[0].geometry.viewport) map.fitBounds(results[0].geometry.viewport);
else if (results[0].geometry.bounds) map.fitBounds(results[0].geometry.bounds);
else map.setZoom(15);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: address
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
};
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
<script src="http://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="pano" style="width: 425px; height: 400px;float:left"></div>
<div id="info"></div>
<div id="map_canvas" style="width: 425px; height: 400px;float:left"></div>
<div id="map_center"></div>
<div id="streetview_pov"></div>

Categories