It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I am trying to build a script that pulls in data from a database using
php/mysql. And I want to create a sidebar with the locations in
my database. Kind of like the example in the link underneath
http://www.geocodezip.com/v3_MW_example_map15c.html
I am able to pull in data and display the locations on my map just
fine ... but the sidebar is not displaying any of my markers I am pretty sure there is a problem with the part of my code that creates the markers.. i'm new to javascript though so could be wrong though. That part of the code can be found on line 36 ... starts off something like
function createMarker(latlng, name, html) {
Here's a link to my script
http://onlineworkplace.info/googlemaps/testing.php
And here is the actual script.
<script type="text/javascript">
var customIcons = {
c: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
u: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
// this variable will collect the html which will eventually be placed in the select
var select_html = "";
// arrays to hold copies of the markers
// because the function closure trick doesnt work there
var gmarkers = [];
// global "map" variable
var map = null;
// A function to create the marker and set up the event window function i am pretty sure something is not right here
function createMarker(latlng, name, html) {
var ContentString = html;
var markers = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(ContentString);
infowindow.open(map,marker);
});
// ======= Add the entry to the select box =====
select_html += '<option> ' + name + '<\/option>';
// ==========================================================
// save the info we need to use later
gmarkers.push(markers);
return markers;
}
// ======= This function handles selections from the select box ====
// === If the dummy entry is selected, the info window is closed ==
function handleSelected(opt) {
var i = opt.selectedIndex - 1;
if (i > -1) {
google.maps.event.trigger(gmarkers[i],"click");
}
else {
infowindow.close();
}
}
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(29.760, -95.387),
zoom: 10,
mapTypeId: 'hybrid'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml2.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("skatespots");
// ==== first part of the select box ===
select_html = '<select onChange="handleSelected(this)">' +
'<option selected> - Select a location - <\/option>';
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var confirmed = markers[i].getAttribute("confirmed");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b>";
var icon = customIcons[confirmed] || {};
// i think the varmarker bit is not right not here not sure though
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
// ===== final part of the select box =====
select_html += '<\/select>';
document.getElementById("selection").innerHTML = select_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() {}
// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/
// http://econym.org.uk/gmap/
// from the v2 tutorial page at:
// http://econym.org.uk/gmap/basic3.htm
Any help or maybe hints as to what is going wrong would be appreciated
Thanks
This answer makes the assumption that by sidebar you mean the select combo box
The original version called
function createMarker(latlng, name, html)
which adds the option to the select box.
You are no longer calling createMarker, but are instead calling
function bindInfoWindow(marker, map, infoWindow, html)
which only adds the 'click' listener, but doesn't do anything else (like adding the option to the select_html variable).
You could just modify your loop:
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var confirmed = markers[i].getAttribute("confirmed");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b>";
var icon = customIcons[confirmed] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
// I have been added so I populate the select combo box.
select_html += '<option> ' + name + '<\/option>';
}
First of all you have inconsistency in createMarker() - first it's 'markers':
var markers = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5 // btw do you really need this??
});
then 'marker':
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(ContentString);
infowindow.open(map,marker);
});
Then, you redeclare your map variable in load() function's scope:
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(29.760, -95.387),
zoom: 10,
mapTypeId: 'hybrid'
}); // creates another variable in local scope
// instead use global variable, meaning you don't redeclare it (don't use 'var'):
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(29.760, -95.387),
zoom: 10,
mapTypeId: 'hybrid'
}); // creates another variable in local scope
Next: you again use inconsistent variables for info window:
var infoWindow = new google.maps.InfoWindow; // btw this one should be global like map
// and elsewhere:
function handleSelected(opt) {
var i = opt.selectedIndex - 1;
if (i > -1) {
google.maps.event.trigger(gmarkers[i],"click");
}
else {
infowindow.close();
}
}
And finally you loop markers got with AJAX and create markers in place instead of using createMarker() function, so replace this:
// i think the varmarker bit is not right not here not sure though
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
with:
createMarker(point, name, html, icon);
and forge createMarker definition as you wish to set icon:
function createMarker(latlng, name, html, icon) {
var ContentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5,
icon: icon.icon,
shadow: icon.shadow
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(ContentString);
infowindow.open(map,marker);
});
// ======= Add the entry to the select box =====
select_html += '<option> ' + name + '</option>';
// ==========================================================
// save the info we need to use later
gmarkers.push(marker);
return marker;
}
Also declare select_html as global variable.
Related
I have tried implementing a marker cluster into my code from the Google Developers Documentation but no joy so far. https://developers.google.com/maps/documentation/javascript/marker-clustering
Here is the snippet of code from my .JS file paying attention to the function showAllCustomers(allData) where I want to implement the Marker Clusterer:
var map;
var geocoder;
//Code to load the map with center point of Monterey MA
function initMap() {
var monterey = {lat: 42.181613, lng: -73.215013};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: monterey,
mapTypeId: google.maps.MapTypeId.HYBRID,
labels: true,
});
//collect customer data and geocoder object - declare geocoder as global
var cusdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
codeAddress(cusdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
showAllCustomers(allData)
var searchData = JSON.parse(document.getElementById('searchData').innerHTML);
showSearchedCustomer(searchData)
}
function showAllCustomers(allData) {
//declare info window variable outside of loop to allow to clear when selecting other markers
var infoWind = new google.maps.InfoWindow;
Array.prototype.forEach.call(allData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = [data.lastName + ' ' + data.physicalAddress];
content.appendChild(strong);
//add image to infowindow - you are also able to add image path to mysql and then append dynamically
var img = document.createElement('img');
img.src = 'images/santahat.png';
img.style.width = '50px';
content.appendChild(img);
//Create markers for customer locations and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
// Add event listener to open info window and show customer name
marker.addListener('mouseover', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
//add event listener to zoom in to clicked customer
google.maps.event.addListener(marker, 'click', function() {
map.panTo(this.getPosition());
map.setZoom(20);
});
});
})
}
Here is my attempt to add the MarkerClusterer (code same as previous up to this point):
//Create markers for customer locations and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
//create marker clusterer to group data
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
// Add event listener to open info window and show customer name
marker.addListener('mouseover', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
//add event listener to zoom in to clicked customer
google.maps.event.addListener(marker, 'click', function() {
map.panTo(this.getPosition());
map.setZoom(20);
});
});
markerCluster.addMarker(marker);
})
}
Functioning JS file:
var map;
var geocoder;
//Code to load the map with center point of Monterey MA
function initMap() {
var monterey = {lat: 42.181613, lng: -73.215013};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: monterey,
mapTypeId: google.maps.MapTypeId.HYBRID,
labels: true,
});
//collect customer data and geocoder object - declare geocoder as global
var cusdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
codeAddress(cusdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
showAllCustomers(allData);
var searchData = JSON.parse(document.getElementById('searchData').innerHTML);
showSearchedCustomer(searchData)
}
function showAllCustomers(allData) {
//declare info window variable outside of loop to allow to clear when selecting other markers
var infoWind = new google.maps.InfoWindow;
//Create marker clusterer to group data
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
Array.prototype.forEach.call(allData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = [data.lastName + ' ' + data.physicalAddress];
content.appendChild(strong);
//add image to infowindow - you are also able to add image path to mysql and then append dynamically
var img = document.createElement('img');
img.src = 'images/santahat.png';
img.style.width = '50px';
content.appendChild(img);
//Create markers for customer locations and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
markerCluster.addMarker(marker);
// Add event listener to open info window and show customer name
marker.addListener('mouseover', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
//add event listener to zoom in to clicked customer
google.maps.event.addListener(marker, 'click', function() {
map.panTo(this.getPosition());
map.setZoom(20);
});
});
})
}
//google maps geocoding code for address to collect lat lng from customer addresses
function codeAddress(cusdata) {
Array.prototype.forEach.call(cusdata, function(data){
var address = data.lastName + ' ' + data.physicalAddress;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
//create object that collects the lat and lng data and pass function to update customers lat lng
var points = {};
points.id = data.id;
points.latitude = map.getCenter().lat();
points.longitude = map.getCenter().lng();
updateCustomersWithLatLng(points);
//add code to check the result status from geocode request and if we get an OVER_QUERY_LIMIT error we try again after slight delay // Jay 20201208-1015
} else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function() {
codeAddress(cusdata);
}, 100);
} // else {
// alert("Geocode was not successful for the following reason:"
// + status);
// }
});
});
}
//create update customers function that updates db using ajax call
function updateCustomersWithLatLng(points) {
$.ajax({
url:"action.php",
method:"post",
data: points,
success: function(res) {
console.log(res)
}
})
}
//When search customers is clicked create function to zoom in to the searched customer
function showSearchedCustomer(searchData) {
// var searchedCus = { ? };
// map = new google.maps.Map(document.getElementById("map"), {
// zoom: 20,
// center: searchedCus,
// });
//declare info window vairable outside of loop to allow to clear if selecting other markers
var infoWind = new google.maps.InfoWindow;
Array.prototype.forEach.call(searchData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = [data.lastName + ' ' + data.physicalAddress];
content.appendChild(strong);
//add image to infowindow - you are also able to add image path to mysql and then append dynamically
var img = document.createElement('img');
img.src = 'images/santahat.png';
img.style.width = '50px';
content.appendChild(img);
//Create marker for searched customer location and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
// Add event listner to open info window and show customer name
marker.addListener('mouseover', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
});
});
}
I am using gmap3 plugin to show google map. In my case I have stored all the information of properties in the database(mysql) with custom markers. Now I want that when the page is loaded it will display all the markers in google map.
For loading googlemap with gmap3 plugin I am using this code
function loadMap() {
jQuery(document).ready(function(){
if(typeof gMap == 'undefined') {
//// CREATES A MAP
gMap = jQuery('#map-canvas');
gMap.gmap3({
map: {
options: {
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
streetViewControl: false
}
}
});
}
});
}
and inside div ``map-canvas I can see the map. But can some one kindly tell me how to show all the markers with the positions? Any help and suggestions will be really appreciable. Thanks.
Update
If I am wrong with my codes then someone can show their codes to me. I am using Gmap3 plugin.
I am not sure about this it will work in gmap3 but i use this code for creating my costome icon hope it will help you
In the index.php use this for creating your costom icon pathlike this
<?php
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
$a=array();
while ($row = #mysql_fetch_assoc($result)){ $a='$row[\'type\']'=>array('icon'=>'$row[\'path\']','shadow'=>'$row[\'path2\']')
}
$a=json_encode($a);
?>
it should be done before js file after that
write this
<script>
var customIcons= <?php echo $a; ?>;
</script>
and finally load your map and infoWindowbox() in that function
function infoWindowbox() {
downloadUrl("xml.php", 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,
animation: google.maps.Animation.DROP
});
markerArray.push(marker);
bounds.extend(marker.position);
bindInfoWindow(marker, map, infoWindow, html);
}
map.fitBounds(bounds);
// var markerCluster = new MarkerClusterer(map, markerArray);
});
}
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() {}
gmap3 initializator has a marker attribute that allows you to create markers.
See example with single and multiple markers here:
http://gmap3.net/en/catalog/10-overlays/marker-41
I think this example might help.
Updated:
If you want to read the data like from database (or) xml, You can then make an ajax request to that page (from any page on your site) using jQuery:
I have an example but this is with xml to get the data from xml file.
$.ajax({
url: 'categories.xml (or) your database path',
type: 'get',
success: function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new GLatLng(lat,lng);
var address = markers[i].getAttribute("address");
var name = markers[i].getAttribute("name");
var html = "<b>"+name+"<\/b><p>"+address;
var category = markers[i].getAttribute("category");
// create the marker
var marker = createMarker(point,name,html,category);
map.addOverlay(marker);
}
// == show or hide the categories initially ==
show("theatre");
hide("golf");
hide("info");
// == create the initial sidebar ==
makeSidebar();
});
});
Like this you may get the data from database also through using queries. Try this one atleast you may get the idea.
The gmaps3 plugin documentation shows how to add markers. If you create an options array in php through ajax/json and feed that to the markers: option your markers should be added.
I'm having a bit of a problem with putting up markers from database i followed this guide https://developers.google.com/maps/articles/phpsqlajax_v3. The page just loads but with no markers, I have also checked if the xml generator was working and Yes it does. Could someone help me out what I'm doing wrong? here is my index file.
<?php include('connection_db.php');?>
downloadUrl("xmlspitter.php", 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>
</head>
<body onload="initialize()">
<div id="contain">
<div id="map_canvas" style="width:500px; height:500px"></div>
</div>
</body>
</html>
Note: xmlspitter.php has correct output from my db. Also if anyone knows any more good tutorials please do tell me thanks.
//EDIT
This is the map from external js
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
and xmlspitter.php if anyone was interested
<?php
include('connection_db.php');
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$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("name",$row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("type", $row['type']);
}
echo $dom->saveXML();
?>
From what you have shown, your java script code is not being run. It should all be placed in the initialize function.
Also you haven't initialized the customIcons variable or given it values. If you are not using it, it can just be removed. It should just use the default marker then.
from guide
Custom Icons
You can specify custom icons and shadows for your markers.
Start by creating an associative array which associates your icons to your type strings: 'restaurant' or 'bar.' This makes the icons easy to reference later when you create markers from the XML.
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
I actually did something similar last year. Though I used php to populate the markers out of the database and not javascript and xml.
Edited: The blog link is no longer valid.
I wonder whether someone may be able to help me please.
I using the code shown below to correctly plot markers retrieved from a MySQL database on a Google Map.
<script type="text/javascript">
//Sample code written by August Li
var icon = new google.maps.MarkerImage("images/location-marker-2.png")
new google.maps.Point(16, 32);
var center = null;
var map = null;
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
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("gmaps-canvas"), {
center: new google.maps.LatLng(0, 0),
zoom: 6,
scrollwheel: true,
draggable: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
<?php
include("admin/link.php");
include("admin/opendb.php");
$query = mysql_query("SELECT * FROM `detectinglocations` WHERE `locationid` = '$lid'");
while ($row = mysql_fetch_array($query)){
$locationname=$row['locationname'];
$osgb36lat=$row['osgb36lat'];
$osgb36lon=$row['osgb36lon'];
echo ("addMarker($osgb36lat, $osgb36lon,'<b>$locationname</b><br/>');\n");
}
mysql_close($connect);
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
What I'm now trying to do is add further functionality that allows users to also click on the map to plot new markers, in essence using the pre-existing marker from the database as a point to work from, performing a reverse geocode.
I've been researching this for a number of days now and I've tried to implement a whole host of tutorials, but I just can't seem to get both parts of the functionality working.
I do know that to enable a on-click event I need to incorporate something along the lines of:
google.maps.event.addListener(map, 'click', function(event) {
marker.setPosition(event.latLng)
geocode_lookup( 'latLng', event.latLng );
});
}
but I must admit I'm a little unsure about what else I need to incorporate.
I just wondered whether someone may be able to take a look at this please, and I'd be very grateful if someone could show me where I've gone wrong.
Many thanks and kind regards
I wrote a separate maps page with just click-to-reverse-geocode functionality
http://jsfiddle.net/ZDQeM/
The address details are confusing to work with, I think. The results are an array, at different levels of precision, one might include the county, another the state, another the street address. Generally I only use results[0]. The details are in the docs: https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingResponses
If you need specific information the sure way to obtain it is iterate through the whole results array until you find what you need (types[] containing postal_code, for example).
google.maps.event.addListener(map, 'click', function(event) {
userMarker = new google.maps.Marker({
map: map,
position: event.latLng
});
geocoder.geocode({'latLng': event.latLng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
alert(results[0].formatted_address);
}
else {
alert("No results");
}
}
else {
alert("Geocoding unsuccessful: Status " + status);
}
});
});
Where in your code?
<script type="text/javascript">
//Sample code written by August Li
var icon = new google.maps.MarkerImage("images/location-marker-2.png")
new google.maps.Point(16, 32);
var center = null;
var map = null;
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
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("gmaps-canvas"), {
center: new google.maps.LatLng(0, 0),
zoom: 6,
scrollwheel: true,
draggable: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
<?php
include("admin/link.php");
include("admin/opendb.php");
$query = mysql_query("SELECT * FROM `detectinglocations` WHERE `locationid` = '$lid'");
while ($row = mysql_fetch_array($query)){
$locationname=$row['locationname'];
$osgb36lat=$row['osgb36lat'];
$osgb36lon=$row['osgb36lon'];
echo ("addMarker($osgb36lat, $osgb36lon,'<b>$locationname</b><br/>');\n");
}
mysql_close($connect);
?>
center = bounds.getCenter();
map.fitBounds(bounds);
var geocoder = new google.maps.Geocoder();
google.maps.event.addListener(map, 'click', function(event) {
var userMarker = new google.maps.Marker({
map: map,
position: event.latLng
});
geocoder.geocode({'latLng': event.latLng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
alert(results[0].formatted_address);
}
else {
alert("No results");
}
}
else {
alert("Geocoding unsuccessful: Status " + status);
}
});
});
}
</script>
Im setting some json using wordpress post data on a page and then passing that json to some JS which loops through and adds markers to a map. I'm so close to getting it working, just need to figure out this last part.
My PHP code to create the json from an array:
<script type="text/javascript">
var markers = <?php echo json_encode($pageposts);?>
</script>
Here is my JS code:
var infowindow = null;
$(document).ready(function(){
initialize();
});
function initialize() {
var centerMap = new google.maps.LatLng(41.141208, -73.263726);
var options = {
zoom: 12,
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map'), options);
setMarkers(map, markers);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i].meta_value),
map: map
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
//infowindow.setContent(this.html);
//infowindow.open(map, this);
});
}
}
If you want to see the page, with the json embedded - check out this link:
http://www.fairfieldctguide.com/test-map
view-source:http://www.fairfieldctguide.com/test-map
Any help would be greatly appreciated!
Jake
google.maps.LatLng expects two numbers as an argument. Currently you are passing in a string which will result in an error. So you need to convert your markers[i].metavalue to two numbers like so:
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
latlng = markers[i].meta_value.split(",")
lat = parseFloat(latlng[0])
lng= parseFloat(latlng[1])
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
//infowindow.setContent(this.html);
//infowindow.open(map, this);
});
}
}
If you don't want to do a converson you could just store lat and lng values as numbers in separate properties. So your json would look like this:
var markers = [{
"ID":"883",
"post_title":"Tucker's Cafe",
"meta_key":"meta_geo",
"lat":41.1674377,
"lng": -73.2236554
}
and you would add a marker like so:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i].lat, markers[i].lng),
map: map
});