How to use google place api for specific city In PHP - php

I want to use google place api for specific city not world wide.
Currently i use below code
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&types=(locality)&input={ahemdabad}" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">

<script>
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title: "hi"
});
}
</script>';

Related

How to add two Google Place Autocomplete search boxes in one page? [duplicate]

This question already has answers here:
Google Maps API autocomplete 2nd address fields on same page
(3 answers)
jQuery and google maps auto complete
(2 answers)
Closed 3 years ago.
I am trying to add two Google Maps Autocomplete search boxes in one html page. However, the moment I copy the same code with same API only one of them works.
<body>
<div class="pac-card" id="pac-card">
<div id="pac-container">
<input id="pac-input" type="text"
placeholder="Enter a location">
</div>
</div>
<div id="map"></div>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var card = document.getElementById('pac-card');
var input = document.getElementById('pac-input');
var types = document.getElementById('type-selector');
var strictBounds = document.getElementById('strict-bounds-selector');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);
var autocomplete = new google.maps.places.Autocomplete(input);
// Bind the map's bounds (viewport) property to the autocomplete object,
// so that the autocomplete requests use the current map bounds for the
// bounds option in the request.
autocomplete.bindTo('bounds', map);
// Set the data fields to return when the user selects a place.
autocomplete.setFields(
['address_components', 'geometry', 'icon', 'name']);
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
radioButton.addEventListener('click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-address', ['address']);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
document.getElementById('use-strict-bounds')
.addEventListener('click', function() {
console.log('Checkbox clicked! New state=' + this.checked);
autocomplete.setOptions({strictBounds: this.checked});
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=My API KEY&libraries=places&callback=initMap"
async defer></script>
I've checked all possible questions in stack with respect to this topic and none of them used an API key which was the main reason for me posting this question. I ran all those codes that I found online but none worked perfectly.
To those who have the same problem as me, Here's the solution..
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Maps API v3 Multiple Autocomplete Inputs</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script
type="text/javascript"
src="/js/lib/dummy.js"
></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=Your API Code &libraries=places"></script>
<style id="compiled-css" type="text/css">
.autocomplete {
width:300px;
}
</style>
<!-- TODO: Missing CoffeeScript 2 -->
<script type="text/javascript">//<![CDATA[
var VanillaRunOnDomReady = function() {
function initialize() {
var acInputs = document.getElementsByClassName("autocomplete");
for (var i = 0; i < acInputs.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(acInputs[i]);
autocomplete.inputId = acInputs[i].id;
google.maps.event.addListener(autocomplete, 'place_changed', function () {
document.getElementById("log").innerHTML = 'You used input with id ' + this.inputId;
});
}
}
initialize();
}
var alreadyrunflag = 0;
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", function(){
alreadyrunflag=1;
VanillaRunOnDomReady();
}, false);
else if (document.all && !window.opera) {
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
var contentloadtag = document.getElementById("contentloadtag")
contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete"){
alreadyrunflag=1;
VanillaRunOnDomReady();
}
}
}
window.onload = function(){
setTimeout("if (!alreadyrunflag){VanillaRunOnDomReady}", 0);
}
//]]></script>
</head>
<body>
<input class="autocomplete" id="ac1" placeholder="Enter your address" type="text">
<br />
<br />
<input class="autocomplete" id="ac2" placeholder="Enter your address" type="text">
<br />
<br />
<input class="autocomplete" id="ac3" placeholder="Enter your address" type="text">
<br />
<br />
<span id="log"></span>
<script>
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "42usv81j"
}], "*")
}
// always overwrite window.name, in case users try to set it manually
window.name = "result"
</script>
</body>
</html>

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'dest_address' cannot be null

I am having a problem inserting data into the DB.
The address box is filled with the exact address from the Google maps. I want to insert into DB, it is showing that my attribute is null.
I don't know to to pass the data from JS the blade or whatever is possible so that the attribute "dest_address" is not null.
script.js
var map;
var myLatLng;
var searchBox;
$(document).ready(function() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 27.72,
lng: 85.36
},
zoom: 15
});
var marker = new google.maps.Marker({
position: {
lat: 27.72,
lng: 85.36
},
map: map,
draggable: true
});
searchBox = new google.maps.places
.SearchBox(document.getElementById('dest_address'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
bounds.extend(place.geometry.location);
//set marker position new
marker.setPosition(place.geometry.location);
}
map.fitBounds(bounds);
map.setZoom(15);
});
google.maps.event.addListener(marker, 'position_changed', function() {
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
$('#lat').val(lat);
$('#lng').val(lng);
});
});
DestinationAdd.blade.php
<div class="form-group row">
<label for="dest_address" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10" >
<input type="text" class="form-control input-sm" id="dest_address">
</div>
<div id="map"></div>
</div>
My controller is fine so far because I tried to insert the longitude and latitude first without inserting the address, and the longitude & latitude were in the DB.
Your input dest_address hasn't name attribute.
<input type="text" class="form-control input-sm" id="dest_address" name="dest_address">
remember ID attr is using only to identify HTML element but you need a name to receive data in the controller.
Please try this and let me know how it works :)

How do I store the data returned by Google Places API to my database?

How do I store the data returned by Google Places API to my database?
This is the HTML code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Creating a Custom jQuery Plugin</title>
<link type="text/css" rel="stylesheet" href="jquery.accordion.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.accordion.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('dl#my-accordion').accordion({open:true});
});
</script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script src="js/script.js"></script>
</head>
<body>
<div id="container"></div>
<div id="gmap_canvas"></div>
<div class="actions">
<div class="button">
<label for="gmap_where">Where:</label>
<input id="gmap_where" type="text" name="gmap_where" /></div>
<div id="button2" class="button" onclick="findAddress(); return false;">Search for address</div>
<form action="save.php" method="post">
<div class="button">
<label for="gmap_keyword">Keyword (optional):</label>
<input id="gmap_keyword" type="text" name="gmap_keyword" /></div>
<div class="button">
<label for="gmap_type">Type:</label>
<select id="gmap_type">
<option value="art_gallery">art_gallery</option>
<option value="atm">atm</option>
<option value="bank">bank</option>
<option value="bar">bar</option>
<option value="cafe">cafe</option>
<option value="food">food</option>
<option value="hospital">hospital</option>
<option value="police">police</option>
<option value="store">store</option>
</select>
</div>
<div class="button">
<label for="gmap_radius">Radius:</label>
<select id="gmap_radius">
<option value="500">500</option>
<option value="1000">1000</option>
<option value="1500">1500</option>
<option value="5000">5000</option>
</select>
</div>
<input type="hidden" id="lat" name="lat" value="40.7143528" />
<input type="hidden" id="lng" name="lng" value="-74.0059731" />
<div onclick="findplaces(); return false;"><input type="submit" value="Search for objects"class="button" id="button1" /></div>
</form>
</div>
</body>
</html>
This is the script
var geocoder;
var map;
var markers = Array();
var infos = Array();
function initialize() {
// prepare Geocoder
geocoder = new google.maps.Geocoder();
// set initial position (New York)
var myLatlng = new google.maps.LatLng(40.7143528,-74.0059731);
var myOptions = { // default map options
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions);
}
// clear overlays function
function clearOverlays() {
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
markers = [];
infos = [];
}
}
// clear infos function
function clearInfos() {
if (infos) {
for (i in infos) {
if (infos[i].getMap()) {
infos[i].close();
}
}
}
}
// find address function
function findAddress() {
var address = document.getElementById("gmap_where").value;
// script uses our 'geocoder' in order to find location by address name
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) { // and, if everything is ok
// we will center map
var addrLocation = results[0].geometry.location;
map.setCenter(addrLocation);
// store current coordinates into hidden variables
document.getElementById('lat').value = results[0].geometry.location.lat();
document.getElementById('lng').value = results[0].geometry.location.lng();
// and then - add new custom marker
var addrMarker = new google.maps.Marker({
position: addrLocation,
map: map,
title: results[0].formatted_address,
icon: 'marker.png'
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
// find custom places function
function findPlaces() {
// prepare variables (filter)
var type = document.getElementById('gmap_type').value;
var radius = document.getElementById('gmap_radius').value;
var keyword = document.getElementById('gmap_keyword').value;
var lat = document.getElementById('lat').value;
var lng = document.getElementById('lng').value;
var cur_location = new google.maps.LatLng(lat, lng);
// prepare request to Places
var request = {
location: cur_location,
radius: radius,
types: [type]
};
if (keyword) {
request.keyword = [keyword];
}
// send request
service = new google.maps.places.PlacesService(map);
service.search(request, createMarkers);
}
// create markers (from 'findPlaces' function)
function createMarkers(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// if we have found something - clear map (overlays)
clearOverlays();
// and create new markers by search result
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
} else if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS) {
alert('Sorry, nothing is found');
}
}
// creare single marker function
function createMarker(obj) {
// prepare new Marker object
var mark = new google.maps.Marker({
position: obj.geometry.location,
map: map,
title: obj.name
});
markers.push(mark);
// prepare info window
var infowindow = new google.maps.InfoWindow({
content: '<img src="' + obj.icon + '" /><font style="color:#000;">' + obj.name +
'<br />Rating: ' + obj.rating + '<br />Vicinity: ' + obj.vicinity + '</font>'
});
// add event handler to current marker
google.maps.event.addListener(mark, 'click', function() {
clearInfos();
infowindow.open(map,mark);
});
infos.push(infowindow);
}
// initialization
google.maps.event.addDomListener(window, 'load', initialize);
I just need an idea on how to dump the data returned by Google Places API in a database. Thanks!
You should post the result you got from google map API to your own server, maybe using your own API, and store it on your server.
Interacting with database via Javascript is although possible, it is not recommended.
As Quentin commented "low security environment is not web programming"
So the best approach is using Web Services (via API)
It seems you need to store lat/lon to your database(if needed parse
the lat/lon returned by Google API).
Then create JSON objects out of it.
Next learn about Ajax,
which is going to send data to, and retrieve data from, a server
asynchronously (in the background) without interfering with the
display and behavior of the existing page.
Hope you understand.

Google Map Fails to Load

I tested this code on a test page but now want to implement it on a page that is called by an overlay (Lightview). The map is not displaying and I do not know why. The overlay spaces the size of a map, but nothing shows. Here is the code:
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<?php
require_once('../maps/google.php');
if(isset($_POST['submit']))
{
$zipcode = $_REQUEST['zipcode'];
$lookupPerformed = false;
if (strlen($zipcode) > 0) {
$geocoder = new Geocoder('mykey');
try {
$placemarks = $geocoder->lookup($zipcode);
}
catch (Exception $ex) {
echo $ex->getMessage();
exit;
}
$lookupPerformed = true;
}
foreach ($placemarks as $placemark) {
$lat = $placemark->getPoint()->getLatitude();
$long = $placemark->getPoint()->getLongitude();
}
?>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
A Company: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(<?php echo $lat;?>, <?php echo $long;?>),
zoom: 10,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("../testxml.php?zipcode=<?php echo $zipcode;?>", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
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);
});
}
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>
///// other PHP code
</head>
<form method="POST" id="ajaxForm" onsubmit="submitAjaxFormDemonstration()">
<input type="text" size="10" maxlength="10" name="zipcode" tabindex="1" value=" <?php echo $_POST['zipcode'];?>" />
<input type="submit" id="submit" value="Search" name="submit" tabindex="2" />
</form>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
You have a pile of things going wrong here, and somethings which I can't even see to tell you whether they are right or wrong...
At the bottom of the posted code, you have:
</head>
<form method="POST" id="ajaxForm" onsubmit="submitAjaxFormDemonstration()">
<input type="text" size="10" maxlength="10" name="zipcode" tabindex="1" value=" <?php echo $_POST['zipcode'];?>" />
<input type="submit" id="submit" value="Search" name="submit" tabindex="2" />
</form>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
You have a <form>...</form> element declared outside of the <body>...</body> tags - this is not valid HTML.
</head>
<body onload="load()">
<form method="POST" id="ajaxForm" onsubmit="submitAjaxFormDemonstration()">
<input type="text" size="10" maxlength="10" name="zipcode" tabindex="1" value="<?php echo $_POST['zipcode'];?>" />
<input type="submit" id="submit" value="Search" name="submit" tabindex="2" />
</form>
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
Fixes that... But you should probably use something like the W3C Validator to check your HTML code. Bad HTML will almost always break Javascript (like Google Maps).
Next, you are invoking a PHP script which you do not explain at all require_once('../maps/google.php');. What is it? Where did you get it? Have you consulted their Tutorials or Documentation?
You are only showing us part of the problem here. You need to go back to Square 1 and check each step as you move forwards. Jumping to the end (which, from the looks of your code, is what you've tried to do) means that one of the hundred steps between Square 1 and there may have broken, and now you have to go back and look for it.

Load mySQL Data Into Form

I am using the PHP and AJAX coding below to populate a map showing various markers for a given location stored in a mySQL database.
The markers are correctly shown but what I would like to be able to do is to populate the fields on my form with the associated data from the database, so that as each marker is clicked the fields will show the data pertient to that marker.
PHP Code
<
?php
require("phpfile.php");
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a MySQL server
$connection=mysql_connect ("hostname", $username, $password);
if (!$connection) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT findid, locationid, findosgb36lat, findosgb36lon, dateoftrip, findcategory, findname, finddescription, pasref, findimage, additionalcomments FROM finds WHERE `locationid` = '2'";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("findid",$row['findid']);
$newnode->setAttribute("locationid",$row['locationid']);
$newnode->setAttribute("findosgb36lat",$row['findosgb36lat']);
$newnode->setAttribute("findosgb36lon",$row['findosgb36lon']);
$newnode->setAttribute("dateoftrip",$row['dateoftrip']);
$newnode->setAttribute("findcategory",$row['findcategory']);
$newnode->setAttribute("findname",$row['findname']);
$newnode->setAttribute("finddescription",$row['finddescription']);
$newnode->setAttribute("pasref",$row['pasref']);
$newnode->setAttribute("findimage",$row['findimage']);
$newnode->setAttribute("additionalcomments",$row['additionalcomments']);
}
echo $dom->saveXML();
?>
HTML Code
<!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>Finds Per Location</title>
<link rel="stylesheet" href="css/findsperlocationstyle.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">
var customIcons = {
Artefact: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Coin: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Jewellery: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
// Creating a LatLngBounds object
var bounds = new google.maps.LatLngBounds();
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:14,
mapTypeId: 'satellite'
});
// Change this depending on the name of your PHP file
downloadUrl("phpfile.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 findid = markers[i].getAttribute("findid");
var locationid = markers[i].getAttribute("locationid");
var dateoftrip = markers[i].getAttribute("dateoftrip");
var findcategory = markers[i].getAttribute("findcategory");
var findname = markers[i].getAttribute("findname");
var finddescription = markers[i].getAttribute("finddescription");
var pasref = markers[i].getAttribute("pasref");
var findimage= markers[i].getAttribute("findimage");
var additionalcomments= markers[i].getAttribute("additionalcomments");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("findosgb36lat")),
parseFloat(markers[i].getAttribute("findosgb36lon")));
var icon = customIcons[findcategory] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
title: 'Click to view details',
icon: icon.icon,
shadow: icon.shadow
});
bounds.extend(point);
map.fitBounds(bounds);
}
});
}
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()">
<form name="findsperlocation" id="findsperlocation">
<p align="left"><label>Location id<br />
</label>
</p>
<div>
<div align="left">
<input name="locationid" type="text" id="locationid" value="2" readonly="readonly"/>
</div>
</div>
<p align="left"><label>Date of Trip<br />
</label>
</p>
<div>
<div align="left">
<input name="dateoftrip" type="text" id="dateoftrip" readonly="readonly"/>
</div>
</div>
<p align="left">
<label></label>
<label>Find Category</label>
</p>
<div>
<div align="left">
<input name="findcategory" type="text" id="findcategory" size="10"readonly="readonly"/>
</div>
</div>
<p align="left">
<label>Find Name</label>
</p>
<div>
<div align="left">
<input name="findname" type="text" id="findname" size="35" readonly="readonly"/>
</div>
</div>
<p align="left"><label>Find Description</label> </p>
<div>
<div align="left">
<input name="finddescription" type="text" id="finddescription" size="100"readonly="readonly"/>
</div>
</div>
<p align="left">
<label>
<label>PAS Ref. </label>
</p>
<div>
<div align="left">
<input name="pasref" type="text" id="pasref" readonly="readonly"/>
</div>
</div>
<p align="left"><label>Additional Comments</label>
</p>
<div>
<div align="left">
<textarea name="additionalcomments" cols="50" rows="12" id="additionalcomments" readonly="readonly"></textarea>
</div>
</div>
<p align="left"><br />
</label>
</p>
<div>
<div align="left"></div>
</div>
</form>
<div id="map"></div>
</body>
</html>
I think I'm half way there because I'm mangaing to pull all of the information from the database. I can see this when I run the php script in my web browser, but I'm just not sure what to do for the next step.
What do I need to do next?
UPDATED CODE
<!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>Finds Per Location</title>
<link rel="stylesheet" href="css/findsperlocationstyle.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">
var customIcons = {
Artefact: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Coin: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Jewellery: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
// Creating a LatLngBounds object
var bounds = new google.maps.LatLngBounds();
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:14,
mapTypeId: 'satellite'
});
// Change this depending on the name of your PHP file
downloadUrl("phpfile.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 findid = markers[i].getAttribute("findid");
var locationid = markers[i].getAttribute("locationid");
var dateoftrip = markers[i].getAttribute("dateoftrip");
var findcategory = markers[i].getAttribute("findcategory");
var findname = markers[i].getAttribute("findname");
var finddescription = markers[i].getAttribute("finddescription");
var detectorname = markers[i].getAttribute("detectorname");
var searchheadname = markers[i].getAttribute("searchheadname");
var detectorsettings = markers[i].getAttribute("detectorsettings");
var pasref = markers[i].getAttribute("pasref");
var findimage= markers[i].getAttribute("findimage");
var additionalcomments= markers[i].getAttribute("additionalcomments");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("findosgb36lat")),
parseFloat(markers[i].getAttribute("findosgb36lon")));
var icon = customIcons[findcategory] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
title: 'Click to view details',
icon: icon.icon,
shadow: icon.shadow,
formdateoftrip: "dateoftrip",
formfindcategory: "findcategory"
});
bounds.extend(point);
map.fitBounds(bounds);
}
google.maps.event.addListener(marker, "click", function() { alert("Associated data: " + this.formdateoftrip + ", " + this.findcategory); });
});
}
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()">
<form name="findsperlocation" id="findsperlocation">
<p align="left"><label>Location id<br />
</label>
</p>
<div>
<div align="left">
<input name="locationid" type="text" id="locationid" value="2" readonly="readonly"/>
</div>
</div>
<p align="left"><label>Date of Trip<br />
</label>
</p>
<div>
<div align="left">
<input name="dateoftrip" type="text" id="dateoftrip" readonly="readonly"/>
</div>
</div>
<p align="left">
<label></label>
<label>Find Category</label>
</p>
<div>
<div align="left">
<input name="findcategory" type="text" id="findcategory" size="10"readonly="readonly"/>
</div>
</div>
</form>
<div id="map"></div>
</script>
</body>
</html>
CODE SNIPPET
var marker = new google.maps.Marker({
map: map,
position: point,
title: 'Click to view details',
icon: icon.icon,
shadow: icon.shadow,
formdateoftrip: "dateoftrip",
formfindcategory: "findcategory",
formfindname: "findname",
formfinddescription: "finddescription",
formpasref: "pasref",
formfindimage: "findimage",
formadditionalcomments: "additionalcomments"
});
bounds.extend(point);
map.fitBounds(bounds);
}
google.maps.event.addListener(marker, "click", function() {
document.getElementById('dateoftrip').value = this.formdateoftrip;
document.getElementById('findcategory').value = this.formfindcategory;
document.getElementById('findname').value = this.formfindname
});
You can store additional data in your marker just by adding new fields like this:
var marker = new google.maps.Marker(
{
map : map,
position : point,
title : 'Click to view details',
icon : icon.icon,
shadow : icon.shadow,
myVariable1 : "some data from xml",
myVariable2 : "some other data"
});
Then all you have to do is register onClick event for the marker and put it's data into the form.
google.maps.event.addListener(marker, "click", function()
{
alert("Associated data: " + this.myVariable1 + ", " + myVariable2);
});
// Edit:
Obviously the code above only shows how to retrieve data from the marker - it was just an example. Putting your data from JavaScript into the form is a 2 step process. The first thing you have to do is to give every field you want to fill an unique id via "id" attribute. You've already done it. Then all you have to do is put following code in the onClick event (instead of alert() in the sample above):
document.getElementById('formdateoftrip').value = this.formdateoftrip;
// repeat it for other fields here
Good luck ;)
// Another edit:
I didn't notice you've put google.maps.event.addListener in wrong place. The reason it works for only one marker is you've put it outside your "for" loop which creates the markers. It has to be inside, right after the "map.fitBounds(bounds);" but before "}", so move it one line up.
The second problem lies in passing the data in the marker. If you want to reference variables, you can't put them in quotes. You use quotes to write strings.
Replace:
formdateoftrip: "dateoftrip",
formfindcategory: "findcategory",
...
Into:
formdateoftrip: dateoftrip,
formfindcategory: findcategory,
// fix the others below too

Categories