How to display multiple colour pins on Google Maps - javascript

I am currently displaying markers on a Google Map successfully, but want to overlay a different set of markers in a different colour for something else but I'm a bit stuck on how to do it.
I am getting the data into the $markers array from a database as follows:
while($row = $result->fetch_row())
{
$rows[]=$row;
$markers[$key] = trim($row[12]).','.trim($row[13]).','.trim($row[10]).','.trim($row[9]).','.trim($row[8]).','.trim($row[4]).','.trim($row[6]).','.trim($row[3]);
$key = $key +1;
}
Where the $row[""] is the data from the database including lat and lon for the marker locations.
The magic then happens in here:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=<?=$api_key?>">
</script>
<script type="text/javascript">
var map;
var marker = {};
function initialize() {
var mapOptions = {
center: { lat: 20.1788823, lng: 13.8262155},
zoom: 2
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var markers = [];
<?php
$counter = 0;
foreach ($markers as $index => $list){
$marker_details = explode(',',$list);
echo 'markers["m'.($index-1).'"] = {};'."\n";
echo "markers['m".($index-1)."'].lat = '".$marker_details[0]."';\n";
echo "markers['m".($index-1)."'].lon = '".$marker_details[1]."';\n";
$counter++;
}
?>
var totalMarkers = <?=$counter?>;
var i = 0;
var infowindow;
var contentString;
for (var i = 0; i<totalMarkers; i++){
contentString = '<div class="content">'+
'<h2 class="firstHeading">'+markers['m'+i].name+'</h2>'+
'<div class="bodyContent">'+
'<p>'+markers['m'+i].content+'</p>'+
'</div>'+
'</div>';
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker['c'+i] = new google.maps.Marker({
position: new google.maps.LatLng(markers['m'+i].lat,markers['m'+i].lon),
icon: {
url: "https://maps.google.com/mapfiles/ms/icons/red.png"
},
map: map,
title: markers['m'+i].name,
infowindow: infowindow
});
//console.log(markers['m'+i].lat+','+markers['m'+i].lon);
google.maps.event.addListener(marker['c'+i], 'click', function() {
for (var key in marker){
marker[key].infowindow.close();
}
this.infowindow.open(map, this);
});
}
}
function panMap(la,lo){
map.panTo(new google.maps.LatLng(la,lo));
}
function openMarker(mName){
//console.log(marker);
for (var key in marker){
marker[key].infowindow.close();
}
for (var key in marker){
if (marker[key].title.search(mName) != -1){
marker[key].infowindow.open(map,marker[key]);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And finally it is rendered with this:
<div id="map-canvas"></div>
I have tried reading the second set of data from another data into $markers2[$key] but I'm then stuck at what to do next, I've tried quite a few different things (too many to list here!) but it either fails to render the new markers of fails to render anything at all on the map.
Any pointers in the right direction would be helpful. I'm not too familiar with javascript unfortunately.

Ok, I found the problem, the issue was that I was creating another "new" map each time and needed to remove the additional instances of :
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
Now the additional markers with the new data display correctly.
Thanks for all the downvotes, it really does concentrate the mind on finding the solution yourself!

Related

Creating an interactive InfoWindow Google Maps API

I'm trying to essentially allow the user to click options in the Google Map infowindow which would alter the content of that infowindow, i.e a page a,b,c inside the infowindow which when initially opened starts on a.
I've tried using jQuery at the top of the page (outside of the infowindow)
of the form
$(document).ready(function(){
$("#other1").click(function(){
$("#thingy").slideToggle("slow");
$("#squirry").slideToggle("slow");
});
});
and giving them id="something" inside the contentvar but to no avail
I've also tried having javascript of the form
function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
return false;
}
inside the infowindow but I just get a whitescreen of death. Is there anyway you can put javascript within the html within the javascript? or anyway to allow the content of an infowindow to be changed from within the window once its already loaded.
Here is the code i'm looking at
its javascript/html nested inside some php
echo "
var myLatLng$i = {lat: $lat[$i], lng: $lng[$i]};
var image = 'nuticon.png';
var address$i = new google.maps.Marker({
position: myLatLng$i,
icon: image,
map: map});
address$i.addListener('click', function() {
document.getElementById('right-panel').innerHTML = '';
var contentString$i =
'<div id=\"content\">'+
'<div id=\"siteNotice\">'+
'</div>'+
'<h1 id=\"firstHeading\" align=\"center\" class=\"h3\">$titles[$i] </h1>'+
'<table border=\"1\" align=\"center\"><tr><p><td><b>Info</b></td><td> <b>Menu </b></td><td><b>Pictures</b></td></p></tr></table>'+
'<div id=\"bodyContent\" align=\"center\">'+
'<p></p>'+
'<iframe id=\"iframe\" src=\"http://voting.first-jump.com/init.php?a=g&g=1000000000004$i&m=0&n=5&s=25&nosound=1&f=3.png&f_a=&f_b=&f_c=\" allowtransparency=\"true\" hspace=\"0\" vspace=\"0\" marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" height=\"38\" scrolling=\"no\" width=\"128\"></iframe>'+
'</div>'+
'<p align=\"center\" id=\"logo\" ><img src=\"$i.png\" width=\"120\" onclick=\"window()\"></p>'+
'<p align=\"center\" id=\"weblink\">Website Link: <a href=\"$websites[$i]\">'+
'$titles[$i]</a> '
'</div>';
var infoWindow$i = new google.maps.InfoWindow({
map: map,
content: contentString$i,
maxWidth: 200
});
infoWindow$i.open(map, address$i);
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: false,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.setOptions( { suppressMarkers: true } );
directionsDisplay.addListener('directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute(pos, '$lat[$i],$lng[$i]', directionsService,
directionsDisplay);
});
";
}}}
?>
for those people trying to add tabs to your infowindow, try the infobubble library provided by Google
http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/examples/example.html/
provides as good a working example as I myself would post.

google.maps.places is undefined

I have a website that loads 3 seperate "views" of a location via Google Maps, Street and Places.
Please see my code below:
I have finally gotten Maps and Street view to work properly but am struggling a bit with this one.
I have a tab that displays the same as map but with places added.
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap"></script>
<script type="text/javascript">
var myLattitude = <?php echo $data["lattitude"]; ?>;
var myLongitude = <?php echo $data["longitude"]; ?>;
var poiMap;
var infowindow;
function initializePoi() {
var poiCentre = new google.maps.LatLng(myLattitude, myLongitude);
poiMap = new google.maps.Map(document.getElementById('poi-canvas'), {
center: poiCentre,
zoom: 15
});
var request = {
location: poiCentre,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(poiMap);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: poiMap,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(poiMap, this);
});
}
Now This initializes properly but the console throws the following error:
TypeError: google.maps.places is undefined
I just want to know why I get this error, I like having clean errorless code.
The places do actually show up properly and everything.
You should add the option libraries=places in the Google API URL
In your case you should replace the following:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap"></script>
With this:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap&libraries=places"></script>
Look at the end of the src=""
Now, you have to use https instead of http.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap&libraries=places"></script>
Everything else is same as previous answer mentioned.
Since the top answer addresses the vanilla version, this is for those using google-maps-react:
add libraries: ['places'] to your GoogleMapReact Component:
<GoogleMapReact
bootstrapURLKeys={{ key: apiKey, libraries: ['places'] }}
...
/>
If you are using React.
import { Wrapper as MapsWrapper } from "#googlemaps/react-wrapper";
// Note libraries prop.
<MapsWrapper apiKey={'YOUR_API_KEY'} libraries={['places']}>
<ChildComponent />
</MapsWrapper>

Google map v2 to v3 code

I am working on a migration project from google maps V2 to V3 and wrote the bellow code but
getting error and unable to solve the problem.
Am i using wrong method of google maps?
What is wrong in this code?
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key='. $mapKey .'&sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( $_ADDRESS );
// initialize map
function initialize()
{
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.getPosition( address, function(point)
{
if (!point)
{
alert(address + " not found");
}
else
{
map.setCenter(point, 13);
var marker = new google.maps.Marker(point);
map.addOverlay(marker);
//marker.openInfoWindowHtml(address);
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Any idesa?
Thanks
I have split these answers as the first deals with the fundamentals of the javascript, this then deals with using the Google Maps API.
As I've never used the maps API, I can't comment on V2, but looking at how you do things in V3, I think this does what you're looking for...
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( "$_ADDRESS" );
// initialize map
function initialize( address )
{
map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.geocode( { "address": address }, function( results, status )
{
if ( status == google.maps.GeocoderStatus.OK )
{
position = results[0].geometry.location;
map.setCenter(position, 13);
var marker = new google.maps.Marker({ map: map, position: position });
}
else
{
alert(address + " not found");
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Having said that, I'd question the str_replace straight into the javascript - can you trust the source of that data? If not, then you should look up how to sanitise that string before you put it into your javascript or you may allow people to inject code into your site.
Looking at the fundamental javascript issues you have...
Try adding quotes around the string that you're replacing into the javascript
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
Becomes:
echo $map = str_replace('$_ADDRESS', "'MYADDRESS'", $map );
That way the string that contains the address in javascript is properly quoted.
Also, ensure that you can receive the address in your initialize function:
function initialize()
Becomes:
function initialize( address )
Finally, do not redeclare "map" when you assign it a value in "initialize", otherwise you are referencing a different variable that only exists in that function:
var map = new google.maps.Map(document.getElementById("map_canvas"), {
Becomes:
map = new google.maps.Map(document.getElementById("map_canvas"), {

Google Map API v3 - Ajax (Javascript + Jquery) GET issue

I am trying to make the map load markers - pulled in from an xml file. It currently does this perfectly. However I also want the map to reload new markers based upon the month passed through from a hyperlink.
When the 'global_month' variable is changed via hyperlink the ajax request fires and the 'data_array' should be repopulated with the new data based upon the date passed to the 'if' statement later on. However it reuses the 'data_array' contents, and doesn't fill it with new data.
I have tried resetting the 'global_month' via 'global_month = []' in the 'change_date_range' function, however - the array doesn't seem to be refilled. I have spent 3 hours trying to work out where I am going wrong, but cannot. Can anyone help? Also is there a more efficient way of doing this?
Thank you very much for you time!
/////////////////////////////////////////////
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "driving_test_centers.xml",
dataType: "xml",
success: parseXml
});
});
var global_month = 6;
function refetch()
{
$.ajax({
type: "GET",
url: "driving_test_centers.xml",
dataType: "xml",
success: parseXml
});
};
var data_array = [];
var empty_holder;
var empty_month;
var info_date;
var address1;
var address2;
var town;
var county;
var postcode;
var lat;
var lon;
var male_pass_percentage1;
var male_pass_percentage;
var female_pass_percentage1;
var female_pass_percentage;
var the_new_date;
var infowindow;
var xml_contents;
function parseXml(xml)
{
$(xml).find("test_center").each(function() // look for all of the test centers
{
center_name = $(this).attr('name');
address1 = $(this).find('address1').text();
address2 = $(this).find('address2').text();
town = $(this).find('town').text();
county = $(this).find('county').text();
postcode = $(this).find('postcode').text();
lat = $(this).find('lat').text();
lon = $(this).find('lon').text();
$(this).find("date_info").each(function()
{
info_date = $(this).attr('date');
empty_month = $(this).find('month').text();
male_pass_percentage = $(this).find('male');
male_pass_percentage = male_pass_percentage.find('pass_percentage').text();
female_pass_percentage = $(this).find('female');
female_pass_percentage = female_pass_percentage.find('pass_percentage').text();
if(empty_month == global_month){
data_array.push([lat,lon,center_name,info_date,male_pass_percentage,female_pass_percentage]);
}
});
});
}
function change_date_range(the_new_date){
global_month = the_new_date;
refetch();
init();
};
</script>
<script>
function init() {
var options = {
zoom: 5,
center: new google.maps.LatLng(55.3781, -3.4360),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var places;
places = null;
var map = new google.maps.Map(document.getElementById('map'), options);
var bounds = new google.maps.LatLngBounds();
var places = data_array;
var temp_location;
for (var i = 0; i < places.length; i++) {
temp_location = new google.maps.LatLng(places[i][0], places[i][1])
// Adding the markers
var marker = new google.maps.Marker({
position: temp_location,
map: map,
title: places[i][2]
});
// Wrapping the event listener inside an anonymous function
// that we immediately invoke and passes the variable i to.
(function(i, marker) {
// Creating the event listener. It now has access to the values of
// i and marker as they were during its creation
google.maps.event.addListener(marker, 'click', function() {
// Check to see if we already have an InfoWindow
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
// Setting the content of the InfoWindow
infowindow.setContent(places[i][2] + "<br />" + global_month + "<br />" + places[i][3] + "<br /><br />Male: " + places[i][4] + "%<br />Female: " + places[i][5] + "%");
// Tying the InfoWindow to the marker
infowindow.open(map, marker);
});
})(i, marker);
// Extending the bounds object with each LatLng
bounds.extend(temp_location);
}
// Adjusting the map to new bounding box
map.fitBounds(bounds)
};
</script>
</head>
<body onload="init()">
<div id="map" style="width:800px;height:600px"></div>
click
</body>
</html>
/////////////////////////////////////////////////////////////
XML file (small part of):
http://tinypaste.com/198889bb
You're not clearing out the data_array array...you just continue to add to it. Why don't you add data_array = []; to the beginning of the parseXml function
edit: you should also clear the markers that are already placed...a good way to make that easy is that when you add markers, hold them in an array, then you can loop through it, setting the map attribute of each to null:
for (x=0;x<markers.length;x++) {markers[x].setMap(null);}

Integrating Google Maps w/ WordPress - Infowindow not opening

I am currently trying to incorporate a map on the homepage of my wordpress blog which will display a custom icon on a map based on a post content and customfield location. I am very close and got everything working except the infowindow. I get no errors and no window. Your help is much appreciated.
I looked at similar questions and tried a few things but nothing worked.
Here is my code:
<script type="text/javascript">
function initialize() {
// setup map
var latlng = new google.maps.LatLng(34.109739, -118.351936);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var infowindow = new google.maps.InfoWindow();
// icons
var bootIcon = '/images/icons/bootIcon.png';
var hikingIcon = '/images/icons/hikingIconSm.png';
// Init post Data
var i = 0;
var hikingPositions = new Array();
var hikingMarkers = new Array();
var hikingBlurbs = new Array();
<?php $hiking_query = new WP_Query('category_name=hiking_ctg&posts_per_page=4');
while ($hiking_query->have_posts()) : $hiking_query->the_post();?>
<?php $geoLoc = get_post_meta($post->ID, 'longlat', true); ?>
// Set Post data
hikingPositions[i] = new google.maps.LatLng(<?php echo $geoLoc; ?>);
hikingMarkers[i] = new google.maps.Marker({
position: hikingPositions[i],
map: map,
icon: hikingIcon,
title:"<?php the_title(); ?>"
});
hikingBlurbs[i] = '<div id="content"><h1 id="firstHeading" class="firstHeading"><?php the_title(); ?></h1><div id="bodyContent"><p>.</p></div></div>';
i++;
<?php endwhile; ?>
// Assign data to map
for(var j=0, marker; j < hikingMarkers.length; j++)
{
// To add the marker to the map, call setMap();
hikingMarkers[j].setMap(map);
marker = hikingMarkers[j];
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(hikingBlurbs[j]);
infowindow.open(map,this);
});
}
}
$(document).ready(function() {
initialize();
});
</script>
I still have a long way to finish all the functionality I am looking for, but for this build, this is the only thing not working.
Thanks in advance.
Regards,
GeneralChaos
I am sure there are more elegant solutions to this, but this worked.
I noticed that the event handler I was using was receiving the index only when the loop was over so I changed the marker to 'this' and added an 'content' value to the marker object.
Define the content array before the marker:
hikingBlurbs[i] = '<div id="infowindowContent"><h1><?php the_title(); ?></h1><div id="bodyContent"><p>.</p></div></div>';
Define your marker with the new content variable:
// Set Post data
hikingPositions[i] = new google.maps.LatLng(<?php echo $geoLoc; ?>);
hikingMarkers[i] = new google.maps.Marker({
position: hikingPositions[i],
map: map,
icon: hikingIcon,
title:"<?php the_title(); ?>",
content: hikingBlurbs[i]
});
Now add the event listener with some simple changes:
// Assign data to map
for(marker in hikingMarkers)
{
google.maps.event.addListener(hikingMarkers[marker], 'mouseover', function() {
infowindow.setContent(this.content);
infowindow.open(map,this);
});
}
Let me know if you see a better way of doing this or you have any questions.
Best Regards,
GeneralChaos

Categories