I am using google maps in one of my jquery mobile pages, and instead of loading the whole maps javascript files on every page, I've included them into the page in which google maps is used.
But when I navigate to the page, the loading spinner is spinning and spinning around but nothing happens. When I delete the gmaps code everything works fine.
I use this plugin so my code looks like that:
<div data-role="page" id="page1" data-theme="a">
<?php include "components/site_header.php"; ?>
<!-- Scripts for Maps -->
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src="library/jquery.ui.map.full.min.js" type="text/javascript"></script>
<!--.................-->
<div data-role="content">
<div id="map_canvas" style="width:100%;height:250px"></div>
<script type="text/javascript">
$(function() {
var LatLng = new google.maps.LatLng(<?=$lat;?>, <?=$lon;?>);
$('#map_canvas').gmap({'center': LatLng});
});
</script>
</div>
</div>
</div>
EDIT The code is working when I call the webpage directly (over the URL). But it is loading endlessly when I navigate to it through the website...
EDIT2 Got the code to work. Removed the plugin which I stated above and added the Google Maps JS file BEFORE the Jquery and Jquery Mobile JS. And my code looks now like this:
<div id="map_canvas" style="width:100%;height:250px"></div>
<script type="text/javascript">
var address = '<?php echo $info['pr_city'].", ".$info['pr_zip'].", ".$info['pr_street'].", ".$info['pr_nr']; ?>';
var map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 15
});
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);
}
});
</script>
Related
I have javascript for a google map and need to put php variables in where the longitude and latitude values are, but I am unsure on how to do allow javascript to work inside a php file, how do I do this?
Here is the code I am using:
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: **-34.397**, lng: **150.644**},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/jskey=MYAPIKEY&callback=initMap"
async defer></script>
What I need is to change the "lat: " and "long: " to have two php variables in it, for example:
lat: $myVariableLat;
lng: $myVariableLng;
And have the javascript above working inside my php file
I'm assuming there's a webserver in your setup running a .php file(s) that is displaying a webpage.
You need to understand that the .php file is just rendering the result of it's contents. This means you need to embed the variable you care about into the html /javascript you're wanting displayed.
If the above is valid, the contents of your .php file would look something like this.
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: <?php echo $myVariableLat; ?>, lng: <?php echo $myVariableLng; ?>},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/jskey=MYAPIKEY&callback=initMap"
async defer></script>
JavaScript runs client-side, PHP gets executed before the document/data is even sent.
If your longitude and latitude don't need to dynamically change then you can use this php code:
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: <?=$myVariableLat?>, lng: <?=$myVariableLng?>},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/jskey=MYAPIKEY&callback=initMap"
async defer></script>
PHP will run and insert the values in your JavaScript.
<?= opens a new php tag and echos the following value. ?> just closes the php tag
The result should look like this:
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/jskey=MYAPIKEY&callback=initMap"
async defer></script>
I have just added bing maps and API to my in development site however I am needing some help understanding how to have my code accept live updating lat and long coordinates and have my map update the marker in regards to these values.
Currently this is what I have but part of the code was designed for google maps which I replaced the words google with Microsoft hoping for the best.
Please be gentle I am new to coding
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=release&callback=loadMapScenario' async defer></script>
</head>
<body>
<div id='printoutPanel'></div>
<div id='myMap' style='width: 400px; height: 400px;'></div>
<script type='text/javascript'>
// Setting boundary and loading map
function loadMapScenario() {
var bounds = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(29.332823, -81.492279), new Microsoft.Maps.Location(28.435825, -81.622231));
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'Bing Maps Key',
maxBounds: bounds
});
// Highlighting the border of bounds on the map
var boundsBorder = new Microsoft.Maps.Polyline([bounds.getNorthwest(),
new Microsoft.Maps.Location(bounds.getNorthwest().latitude, bounds.getSoutheast().longitude),
bounds.getSoutheast(),
new Microsoft.Maps.Location(bounds.getSoutheast().latitude, bounds.getNorthwest().longitude),
bounds.getNorthwest()], { strokeColor: 'red', strokeThickness: 2 });
map.entities.push(boundsBorder);
}
</script>
<script>
function getReverseGeocodingData(lat, lng) {
var latlng = new Microsoft.maps.LatLng(lat, lng);
// This is making the Geocode request
var geocoder = new Microsoft.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status !== Microsoft.maps.GeocoderStatus.OK) {
alert(status);
}
// This is checking to see if the Geoeode Status is OK before proceeding
if (status == Microsoft.maps.GeocoderStatus.OK) {
console.log(results);
var address = (results[0].formatted_address);
}
});
}
</script>
The Bing Maps V8 team actually has a documented code sample on how to do exactly this here: https://msdn.microsoft.com/en-us/library/mt712803.aspx
I'm using google maps api and I need to keep the last center and zoom level everytime I reload the page.
I have this parameters in PHP variables, how can I change initMap function and pass these parameters to it?
The problem is that we are calling the function this way:
<script src="https://maps.googleapis.com/maps/api/js?key=*******&callback=initMap" async defer></script>
You can't pass arguments to the callback(at least not via the way you load the maps-API)
A possible workaround: store the parameters as attribute of the script-tag, then you'll be able to access them in the callback:
<?php
//your parameters, defined in PHP
$goo=array('zoom'=>14,'center'=>array('lat'=>52.549,'lng'=>13.425));
?>
<div id="map_canvas"></div>
<script>
function initMap(){
var opts = {
zoom: 0,
center: new google.maps.LatLng(0,0),
mapTypeId: google.maps.MapTypeId.ROADMAP
},
script= document
.querySelector('script[src^="https://maps.googleapis.com/maps/api/js"][data-goo]'),
custom;
if(script){
custom=JSON.parse(script.getAttribute('data-goo'));
for(var k in custom){
opts[k]=custom[k];
}
}
map = new google.maps.Map(document.getElementById('map_canvas'),
opts);
}
</script>
<script data-goo="<?php echo htmlentities(json_encode($goo));?>"
src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=***" async defer>
</script>
Another option would be the loader of the JSAPI, where you have the option to define a function-reference(instead of a function-name) as callback:
<?php
//your parameters, defined in PHP
$goo=array('zoom'=>14,'center'=>array('lat'=>52.549,'lng'=>13.425));
?>
<div id="map_canvas"></div>
<script>
function initMap(params){
var opts = {
zoom: 0,
center: new google.maps.LatLng(0,0),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
for(var k in params){
opts[k]=params[k];
}
map = new google.maps.Map(document.getElementById('map_canvas'),
opts);
}
</script>
<script src="https://www.google.com/jsapi"></script>
<script>
google.load('maps',
'3',
{ other_params :'key=***',
callback : (function(params){return function(){initMap(params);}})
(<?php echo json_encode($goo);?>) });
</script>
However, as it sounds the desired data(last zoom/center) at first is available on clientSide, so there is no reason to store it on serverSide.
Just store it via sessionStorage(as suggested by #RamRaider ) or even cookies, and read it from the client when you need it.
I have a google map script that works, but I can't figure out how to add it to my asp.net content page. What is the proper way to add the script to the page?
see code:
<%# Page Title="Our Location" Language="VB" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="false" CodeFile="Location.aspx.vb" Inherits="About_Location" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
##map{ height: 100% }
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server" OnLoad="codeAddress()">
<script type= "text/javascript">
var geocoder;
var map;
var marker;
function codeAddress() {
alert("hello")
//initializes the map
//create geocoder
geocoder = new google.maps.Geocoder();
//set options for the map being created
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//create map instance and pass it the myOptions object literal
map = new google.maps.Map(document.getElementById("map"), myOptions);
//geocode to get the lat and lng points of the given address
geocoder.geocode({ 'address': 'New York, New York'}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//if geocoder finds location
//center the map on the latlng points of the given address
map.setCenter(results[0].geometry.location);
map.setOptions({ zoom: 18 });
//create marker and place it on the address
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: 'New York, New York'
});
}
else {
//if geocoder cannot find location, alert user
alert("Could not find location");
}
});
}
</script>
<div id="map" style="width:700px; height:400px;"></div>
</asp:Content>
Put your script in separate js file, declare it like you did with Google maps script. Then you have to call it, maybe send this "#map" div id as parameter to that script, and not hard code it in javascript.
in this case you want to do that on page load with script manager :
ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowGoogleMap", "codeAddress('map');", true);
btw. for google maps you can use Google Maps server control, it's much easier to use managing maps from server side:
http://googlemap.codeplex.com/
I am very new in HTML5 area, I am trying to make a program that will fetch the data from mysql with PHP and use geocode to transform from address to Latlng. it is a LBS program, and I was trying for 2 weeks, my question is I cannot put markers into the Google MAP, I did the locator corrected and map is loaded, but the marker cannot land on map, please help!! thank you, and I am really appreciate your help. if this code has any mistake or problem please give me generous advice, I am very new in this area, and I am trying to learn more in HTML5 Javascript, thank you and I am very appreciate your advice!!!
my code is here:
'enter code here`<?php
require_once 'Common/system_start.php';
$sql="select addr from tab_mem order by sn desc ";
$result= mysql_query($sql);
$data=mysql_fetch_assoc($result);
$row=mysql_num_rows($result);
$n = array();
for($i=0;$i<$rows;$i++)
{
$data=mysql_fetch_row($result);
$n[] = $data[0];
}
echo '<script type="text/javascript">';
echo var n = new Array("', join($n,'","'), '");';
echo '</script>';
?>
<code>
<pre>
<!DOCTYPE html>
<html><head><meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0,user-scalable=no"/>
<!-- Google Maps -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js? `enter code here`sensor=true"></script>
<script type="text/javascript" charset="utf-8" src="cordova-1.6.0.js">
</script>
<!-- program main -->
<script type="text/javascript">
var iterator=0;
markers=n;
var a=n.length;
function load() {
var map_div = document.getElementById("map_div");
//initial locator
navigator.geolocation.watchPosition(onSuccess, onError, { frequency: 3000 `enter code here`});
// decide location
function onSuccess(position){
//fetching latlng from GPS
var latlng = new google.maps.LatLng(position.coords.latitude,
`position.coords.longitude);
// display map
var gmap = new google.maps.Map(
map_div, {
zoom:16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//drop the marker
function drop() {
for (var i = 0; i < a; i++) {
setTimeout(function() {
}, i * 200);
}
}
//decode address to latlng
//pass address data from PHP
for(var i in n){
var address=n;
geocoder=new google.maps.Geocoder();
geocoder.geocode({'address':address},function(results,status){
if(status==google.maps.GeocoderStatus.OK){
//alert("AAA");
address=results(i).geometry.location;
function addMarker() { markers.push(new google.maps.Marker({
postion:results(i).geometry.location,
map:gmap,
animation:google.map.animation.DROP
//iterater++;
}));
//itertor++;
}
//markerNearBy.setMap(map);
}else{
alert("Geocode was not sucessful for the following reason:"+status);
}
});
}
}
}
function onError(error) {
alert('code: '+ error.code+ '\n'
+'message: ' + error.message + '\n');
}
</script>
</head>
<body onLoad="load()">
<!-- Map Display place -->
<div id="map_div" style="width:320px; height:480px;"></div>
</body>
</html>
<code>
Your code doesn't look well-formed. You have the "addMarker" function defined inside your "for" loop. Also, it's not getting called anywhere.
Take a look at the sample code Google provides for working with markers and overlays and try to emulate it. The sample only uses one marker, but you can simply iterate through your results. You've got the right intentions by adding your Marker objects to an array, and setting your map object to the map property of the Marker, but you will need to format/restructure your code first or it will not work.
Sample code:
https://developers.google.com/maps/documentation/javascript/overlays#RemovingOverlays