Manipulating map using buttons - php

GD All,
I've been experimenting with google maps over last few days and was tring to get some interaction with the map by using a button to either drop a marker or draw a path.
From scouting around here and reading several posts I can find numerous options though all tell more or less same story, it should be relatively simple...
Unfortunately I have been unable to produce the desired result so far..:-(
I've tried several things:
- adding alerts, so I can see if the function is actually called = ok!
- integrating the code from the function in the initialize(), to check if the function code is ok = ok!
Yet still cannot seem to get it working...
So, the buttons do call the functions, yet they do not seem to update the map after the function call. I.e. there is nothing changing on the map...?
Any help will be much appreciated.
Basically they 'click listener in the initialize does the same as the 'callMe' function
Yet if I have the listener refer to the 'callMe' function it does not execute, eventhough the alert box triggers, a.k.a. the function is properly called.
My .php code:
<!DOCTYPE html>
<html>
<head>
<title>Simple click event</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title: 'Click to zoom'
});
google.maps.event.addListener(map, 'center_changed', function() {
// 3 seconds after the center of the map has changed, pan back to the
// marker.
window.setTimeout(function() {
map.panTo(marker.getPosition());
}, 3000);
});
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(8);
map.setCenter(marker.getPosition());
});
}
function callMe(){
alert('function called');
map.setZoom(8);
map.setCenter(marker.getPosition());
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="width: 100%; height: 300px"></div>
<div>
<button id="btnOK" onclick="callMe()">Drop marker</button>
</div>
</body>
</html>
Many thanks !
Martijn

Your map variable is defined within the scope of the initialize function and is therefore not reachable inside callMe. You'll need to move the the definition outside initialize, or add a DOM listener inside that function to handle the button click.

Related

Google Maps geocoding : "google is not defined"

I'm getting an issue when I try to load this code, and I can't figure why it doesn't work...
<script type="text/javascript">
$(document).ready(function()
{
var geocoder = new google.maps.Geocoder();
$(".textarea-autosize").autosize();
geocoder.geocode({
address: '{$order->address_delivery["address1"]},{$order->address_delivery["postecode"]},{$order->address_delivery["city"]}'
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK)
{
var delivery_map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: results[0].geometry.location
});
var delivery_marker = new google.maps.Marker({
map: delivery_map,
position: results[0].geometry.location,
url: 'http://maps.google.com?q={$order->address_delivery["address1"]},{$order->address_delivery["postcode"]},{$order->address_delivery["city"]}'
});
google.maps.event.addListener(delivery_marker, 'click', function() {
window.open(delivery_marker.url);
});
}
});
});
// Fix wrong maps center when map is hidden
$('#tabAddresses').click(function(){
x = delivery_map.getZoom();
c = delivery_map.getCenter();
google.maps.event.trigger(delivery_map, 'resize');
delivery_map.setZoom(x);
delivery_map.setCenter(c);
});
</script>
The error occurrs on the var geocoder = new google.maps.Geocoder();
Then I tried to load the following script : <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
and I get another error :
'Uncaught TypeError: Cannot read property 'offsetWidth' of null'
Does anyone has any idea of why it doesn't work ?
Google maps aren't loaded at the time when you're trying to call it. You should be using this:
HTML:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&callback=initMap" async defer></script>
JS:
function initMap() {
// Google maps are now initialized.
}
You need to include the async and defer attributes into your script - this will make sure that the rest of the website keep loading instead of waiting for the script to load (which is handy, because it's quite big).
Secondly, you pass the "callback" parameter when calling the script. This is the name of the function that should be executed when the script is loaded. This way you can make sure you only initialize the map when it's actually loaded and present within your window.
Simply add this script to your html file:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
If you want to test the google geocoding api or check out some code, check out this link. Google Geocoding Service API Source

Google Map showing only in Firefox

i have a facebook app using Heroku and i use a google map for it. The google map is displayed only in Firefox Browser. Chrome an IE will not display it!
I can't understand why and i need your help!
https://apps.facebook.com/sectorsase/
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://maps.google.com/maps/api/js?sensor=false'></script>
<script>
function initialize()
{
var IPos=new google.maps.LatLng(4.256,4.568);
var mapProp = {
center:new google.maps.LatLng(44.438683,26.027269),
zoom:13,
disableDefaultUI:true,
draggable: false,
zoomControl: false,
scrollwheel: false,
disableDoubleClickZoom: true,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById('googleMap'),mapProp);
var marker=new google.maps.Marker({
position:IPos,
icon:'icn.png'
});
var myCity = new google.maps.Circle({
center:IPos,
radius:3,
strokeColor:'#0000FF',
strokeOpacity:0.8,
strokeWeight:2,
fillColor:'#0000FF',
fillOpacity:0.4
});
myCity.setMap(map);
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.trigger(map, 'resize');
</script>
</head>
<body>
<center><div id='googleMap' style='width:500px;height:380px;'></div></center>
</body>
</html>
IE ERROR:
SEC7111: HTTPS security is compromised by http://maps.google.com/maps/api/js?sensor=false
map.php
SCRIPT1002: Syntax error
map.php, line 17 character 33
CHROME ERROR:
[blocked] The page at https://quiet-everglades-2697.herokuapp.com/map.php ran insecure content from http://maps.google.com/maps/api/js?sensor=false. map.php:1 Uncaught ReferenceError: google is not defined map.php:49
With the errors you've provided, I'm going to assume the page you're viewing is HTTPS. You're loading the Google Maps API from a non-HTTPS source. Just change the script tag to https://maps.google.com/maps/api/js?sensor=false. Or better //maps.google.com/maps/api/js?sensor=false which will automatically fill in the http or https for you.

Load Dynamic Google Markers From MySQL

I wonder whether someone could help me please.
I'm using the script below to dynamically load Google markers from a MySQL database and the script works fine.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Map My Finds - My Finds Per Location</title>
<link rel="stylesheet" href="myfindsperlocation.css" type="text/css" media="all" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript">
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:14,
mapTypeId: 'satellite'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("loadmyfindsperlocation.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var locationid = markers[i].getAttribute("locationid");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("findosgb36lat")),
parseFloat(markers[i].getAttribute("findosgb36lon")));
var marker = new google.maps.Marker({
map: map,
position: point
});
bounds.extend(point);
map.fitBounds(bounds);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker, html);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body onLoad="load()">
<div id="map"></div>
</body>
</html>
You'll see it's a relatively simple form, which calls the data from an external PHP file which is shown in my script here: downloadUrl("loadmyfindsperlocation.php", function(data) {
What I'm now trying to do is incorporate the PHP script into the above, but I can't seem to get the map to load and I suspect it's something to do in calling the file as a URL.
Forgive me for asking, I'm relatively new to PHP an XML, but could someone perhaps tell me please how I could call this without loading it as an external URL.
Many thanks and kind regards
I don't have either your CSS or PHP so I can only guess. Do you see errors in your Javascript console?
What I did was add the following styles and the map loaded, even with the PHP missing and giving me errors.
html, body, #map { margin: 0; padding: 0; height: 100% }
About loading the PHP, it has to be served to return a meaningful XML. You can have a pre-written XML and load that too.

Drawing markers on a google map starting from a php array

All right, I'll try to explain my problem as clearly as I can. I already tried a lot of possible solution but never happen to find the right one.
I also want to say this is a tutorial for me, i am just a beginner in combining JS, PHP and GMAPv3 APIs.
I hope that someone can help me in solving this.
That being said, here is my code with a few lines to explain what i want to do.
The problem involves 3 main files.
1) process.php (this file generates an array of coordinates)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>MyTest</title>
<link rel="stylesheet" type="text/css" href="css/content.css" />
<script type="text/JavaScript" src="js/gmapinit.js"></script>
</head>
<body>
<?php
...after some lines of code i build this...
$myarray = ...;
...and here i move to the second file
echo "<input type=\"button\" value=\"Next!\" onClick=\"location.href='map.html'\">";
?>
</body>
2) map.html (this file is responsible for drawing the map on the screen)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>MyTest</title>
<link rel=stylesheet type="text/css" href="css/googlemap.css" />
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCbNM4y2fJ4AdCoXcWW-sGXPl5nXaJogPA&sensor=false">
</script>
<script type="text/JavaScript" src="js/gmapinit.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
</head>
<body onLoad="init_map_and_markers()">
<div id="map_canvas">
</div>
</body>
2) gmapinit.js (the javascript file that builds the map and "should" get the array as parameter to draw markers accordingly)
function init_map_and_markers() {
var global_markers = [];
var infowindow = new google.maps.InfoWindow({});
var latlng = new google.maps.LatLng(27.059126, -41.044922);
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
//Of course here myarray is not defined but the point is making it available here so i can loop through it and place my markers!
for (var i = 0; i < markers.length; i++) {
for(var count = myarray.length - 1; count >= 0; --count) {
var o = myarray[count];
var lat = parseFloat(o.lat);
var lng = parseFloat(o.lng);
var markerdata = o.user;
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + markerdata + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " | Marker Data: " + markerdata
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
}
So the main question is, how can i pass $myarray from process.php to map.html making it available to gmapinit.js???
I am asking this avoiding to write down all code-tests i did because maybe my all thinking is wrong...that's why i am writing down the most "clean" code i got.
Code possible solutions would be much appreciated, and don't hesitate to ask for details if i missed something.
Thanks a lot.
you may use the markers as argument for init_map_and_markers()
<body onLoad="init_map_and_markers(<?php echo json_encode($phpArrayMarkersDefinition); ?>)">
..then you may access this array inside the function:
function init_map_and_markers(markers)
{
//....
for(var i=0;i<markers.length;++i)
{
//create the markers here
}
//....
}

Google map plotting

I was wondering if anyone has any ideas/tutorials on how to plot various points on a google map, and save the points in a database with custom marker titles.
I want something similar to http://www.mapmyrun.com/create_new , where i can actually draw on a map and mark out paths and such.
Plotting the points is done in Javascript, I managed to learn everything I needed from the maps API docs:
http://code.google.com/apis/maps/documentation/javascript/basics.html
I scraped the code below off a site I made which moves a single point to where the mouse is clicked. You should be able to store a set of points in a JS array, or better, get them from the map when submitting your form then update a hidden form field with the values which can be inserted in your database with a php/python script on the server.
<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:400px; height:600px; display:block; float:left">
</div>
</body>
</html>
<script type="text/javascript">
var map;
var marker = null;
function initialize() {
var myLatlng = new google.maps.LatLng(54, -2.0);
var myOptions = {
zoom: 6,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var clickedLocation = new google.maps.LatLng(location);
if(marker == null){
marker = new google.maps.Marker({
position: location,
map: map
});
}else{
marker.setPosition(location);
}
map.setCenter(location);
}
</script>
Edit:
Here is a demo from docs site, which creates a list of points and draws a lines between them:
http://code.google.com/apis/maps/documentation/javascript/examples/polyline-simple.html
There are other examples there too. Just load them and press ctrl+u in firefox to view the source.

Categories