Google Maps Api adding label - google-maps

i'm using the the following function to create my markers from a XML file. i wish to label each market 1,2,3,4,5,6 etc where 'i' is the number. can some please please tell me how to incorporate this. thank you
function createMarker(point, name, address, type, i) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b> <br/>" + address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}

You can use Google's Chart server to create dynamic icons, and set that as your marker image.
Chart server docs on using dynamic icons: http://code.google.com/apis/chart/docs/gallery/dynamic_icons.html
For example,
http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=1|FF0000|000000 will render as
and http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=2|FF0000|000000 will get you

You can make your own Marker icons, and implement them onto your map, see here
(It might be best to use the current Google Maps API v3 if you aren't already)
Do something like:
function createMarker(point, name, address, i) {
var image = "icon" + i + ".png";
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
position: point,
map: map,
icon: image,
title: name
});
addinfowindow(marker, html);
return marker;
}
(where you have made an icon for each marker called icon1.png to icon6.png and placed in the directory)
Also for multiple info windows you may need to create a new global function addinfowindow() with a infowindow defined globally (see here).
function addwindow(pmarker, phtml){
google.maps.event.addListener(pmarker, 'click', function() {
infowindow.setContent(phtml);
infowindow.open(map, pmarker);
});
}

Related

Google Maps V3 InfoWindow ignores latLng position

My map has no markers. In response to a click on the map, it pops up an infowindow with Lat/long shown in decimal to 5 dp and in Degrees minutes seconds. An open window is always closed prior to responding to a new click. The position is specified by position: latLng, but the infowindow is ALWAYS at the top left. I've spent days on this, and I feel I'm missing something. Code snippet below. Any ideas?
google.maps.event.addListener(map, 'click', function (event) {
var lat = event.latLng.lat(),
lng = event.latLng.lng(),
latLng = event.latLng,
strHtml;
//
// strHtml build code omitted but succesfully uses lat and lng to produce
// e.g. Latitude : 51.72229 N (51° 43' 20'' N)
// Longitude : 1.45827 E (1° 27' 30'' E)
//
// If an infowindow is open, then close it
if (openedInfoWindow != null) openedInfoWindow.close();
// latLng monitored to check it is there before use in infowindow
alert(latLng); // returns correct values which position then ignores!
var infoWindow = new google.maps.InfoWindow({
position: latLng,
content: strHtml,
maxWidth: 420
});
// Open infoWindow
infoWindow.open(map,this);
// Remember the opened window
openedInfoWindow = infoWindow;
// Close it if X box clicked
google.maps.event.addListener(infoWindow, 'closeclick', function() {
openedInfoWindow = null;
});
});
You have several problems with this code. The second parameter of the infowindow's open method has to be an MVCObject in the Core API only the Marker class can be used as an anchor. You should not need to set the infowindow variable to null and create a new infowindow object each time. You only need a single infowindow and then change its content and position. This way there is only one infowindow shown at a time.
Here is a fiddle of a working example: http://jsfiddle.net/bryan_weaver/z3Cdg/
relevant code:
google.maps.event.addListener(map, 'click', function (evt) {
var content = "<div class='infowindow'>";
content += "Latitude: " + evt.latLng.lat() + "<br/>";
content += "Longitude: " + evt.latLng.lng() + "</div>";
HandleInfoWindow(evt.latLng, content);
});
function HandleInfoWindow(latLng, content) {
infoWindow.setContent(content);
infoWindow.setPosition(latLng);
infoWindow.open(map);
}
The 2nd (optional)argument of infoWindow.open() is expected to be an MVCObject that exposes a position-property.
the this argument in the callback refers to a google.maps.Map-Instance(map), which is an MVCObject, but doesn't have a position-property.
Remove the 2nd argument from infoWindow.open(map,this); .

Adding Google Maps V3 User input through a searchbox

So, I found some instructions around and a few questions that seemed to answer this question, but none really worked for me or were very incomplete. I'm seeking a way to display the traditional google maps interaction of search and a pin is displayed on the map at the location. This marker, then, should be a blank option to include the data a user wants and the location saved to my database. I tried this sample by Google Dev and it worked for a custom click on the map, but the integration with a simple auto-complete search or even the google's own autocomplete search didn't quite worked.
I was wondering if there is a plugin or a technique (or a tutorial) that would suit this case (that I previously thought would be a simple matter as it is the traditional search on google maps). Thanks!
I can show you how I did this page http://www.a-zhotels.net/register, you could easily combine all the fields into one autocomplete address field. However, this should give you an idea.
First, create a function:
function getMapByGeoLocation() {
//build the address using many fields.
var postcode = $("#HotelPostcode").val();
var address = $("#HotelAddress").val();
var town = $("#HotelTown").val();
var city = $("#HotelCity").val();
var country = $("#HotelCountryId > option:selected").text();
var fulladdress = address + ', ' + town + ', ' + postcode + ', ' + city + ', ' + country;
geocoder.geocode(
{
'address': fulladdress
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
console.log(location);
//map and marker should be previously created
map.setCenter(location);
map.setZoom(14);
marker.setPosition(location);
//These 2 hidden inputs will be posted to the server
$("#HotelLatitude").val(location.Ya);
$("#HotelLongitude").val(location.Za);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
This function is then called when the textbox and dropdowns change:
$("#HotelTown, #HotelAddress, #HotelPostcode").change(getMapByGeoLocation);
See below the function that creates the map:
var map;
var marker;
var geocoder;
function createMap() {
if (map) { //Map already exists
return;
}
if (!$('#mapCanvas').is(':visible')) {
return;
}
var mapCanvas = $("#mapCanvas")[0];
var averageLatitude = $("#HotelLatitude").val();
var averageLongitude = $("#HotelLongitude").val();
map = new google.maps.Map(mapCanvas, {
streetViewControl: true,
zoom: 13,
scrollwheel: false,
center: new google.maps.LatLng(averageLatitude, averageLongitude)
});
geocoder = new google.maps.Geocoder();
//Associate the styled map with the MapTypeId and set it to display.
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
marker = new google.maps.Marker({
position: new google.maps.LatLng(averageLatitude, averageLongitude),
draggable: true,
map: map
});
google.maps.event.addListener(marker, "dragend", function () {
var position = marker.getPosition();
map.panTo(position);
$("#HotelLatitude").val(position.lat());
$("#HotelLongitude").val(position.lng());
});
google.maps.event.addListener(map, "center_changed", function () {
var position = map.getCenter();
marker.setPosition(position);
$("#HotelLatitude").val(position.lat());
$("#HotelLongitude").val(position.lng());
});
}
createMap();
I am not sure what exactly you are looking for.
If you are looking for autocomplete field that adds a marker to the map after the user entered some string and opens an infowindow with a form on the map, is may be something like that: http://jsfiddle.net/XG9Qj/2/
It is important to notice, that this example only places a marker on the map if the user selected one of the suggestions from the autocomplete. To allow him to enter an arbitrary string you have to watch the input for RETURN and use the google maps geocoder on your own(1).
var geocoder = new google.maps.Geocoder();
geocoder.geocode(...)

Google Maps API V3: Create Marker HTML based on search if/else

I have a "store locator" setup here:
http://www.brynei.com/fertdealer_map_bry.htm
lat, lng, name, address, csz, and phone information is stored in a mySQL database. If you input zip code 13165, the locator works as it should. However, I need to limit a range of zip codes to show one marker, and display the marker html for a range of zip codes (66000 to 69999). This part is actually working to center the map using the function searchLocations() section, but I need some help in the function createMarker(latlng, name, address, csz, phone) and function createOption(name, distance, num) section.
Currently if you use zip code 67501, the map will center but no marker is displayed. I need it to place a marker in a specific location, and Company Name Inc, 123 Main St, Anywhere KS 67501, 555-555-1234 as the marker HTML. That marker would be static if a zip is used in the 66000 to 69999 range.
I can do something on the database side also if that is an easier solution.
Any help is appreciated.
These are the 3 sections (functions) I am having an issue with:
function searchLocations() {
var address = document.getElementById("addressInput").value;
var mylatlng = new google.maps.LatLng(37.928552, -97.898658);
var geocoder = new google.maps.Geocoder();
if (address >= 66000 && address <= 69999) {
map.setCenter(mylatlng);
map.setZoom(10); }
else {
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location); }
else {
alert(address + ' not found');
}
});
}}
function createMarker(latlng, name, address, csz, phone) {
var html = "<font face = 'arial'>" + "<b>" + name + "</b> <br/>" + address + "<br/>" + csz + "<br/>" + phone + "</font>";
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
locationSelect.appendChild(option);
}

Google maps infowindow JSON problem

I have recently set up a mobile version of my site and am having a little trouble with the Google Maps V3 infowindows on the mobile version.
I am trying to add some data from my JSON file to appear in the infowindows. I am totally new to JSON and javascript as well really.
Here is the content string that I have for the infowindows on my main desktop site which is working perfectly.
var contentString = '<div align="left"><p style="color:#000000;"><a href="http://publicaccessgolf.com.au/' + data.course[i].slug + '" >' + data.course[i].name + '</a><br />' + data.course[i].address + '<br />' + data.course[i].contact + '</p></div>';
I want to add this to my mobile site but it will not work, the map either doesn’t display at all or there are no markers displayed.
Here is part of the code for my mobile site
function addMarker(map, position){
var marker = $('#map_canvas').gmap('addMarker', { 'position': position });
var contentString = 'Need to add info in here...' ;
var infoWindow = $('#map_canvas').gmap('addInfoWindow', { 'position':marker.get(0).getPosition(), 'content': contentString });
marker.click(function() {
infoWindow.get(0).open(map, marker.get(0));
map.panTo(marker.get(0).getPosition());
});
}
Any ideas why the code from the normal site would not be working??
Could there be problems with the content, e.g. an apostrophe in data.course[i].name?
Have you tried just doing this (to replace your marker.click() function):
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(contentString);
infoWindow.open(map, this);
map.panTo(marker.get(0).getPosition());
});
You can access the data of a google.maps.data layer added as geoJson just by calling event.feature.getProperty('nameofproperty'). Where 'nameofproperty' could be numer or string (the name of property in your geoJson-file).
Here a simple example I'm using that works fine:
//Load mapdata via geoJson
myDataLayer = new google.maps.Data();
myDataLayer.loadGeoJson("myData.geojson");
var featureStyle = {
icon: "mm_purple.png"
};
myDataLayer.setStyle(featureStyle);
myDataLayer.setMap(map);
//listen for click events and show infowindow
var infoWindow = new google.maps.InfoWindow();
myDataLayer.addListener('click', function(event) {
infoWindow.setContent('first property: '+ event.feature.getProperty('myfirstproperty') +'<br /> second proporty: '+ event.feature.getProperty('mysecondproperty') +
'<br /> last property: '+ event.feature.getProperty('mylastproperty'));
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
});

Display multiple markers on google map by providing address

I have the following script to use the google maps API, I have to create a map that has more than one Marker (the balloon shaped icon pointing to something) and i need each of those markers to point on a different area of the map (i.e. different coordinates), how can i do it?
NOTE: I do not have latitude and longitude for the area on which marker has to be placed instead I have the address of the area on which marker has to be placed.
The code to display multiple markers on Google map is given below but it does not work as expected!
var map = null;
var geocoder = null;
function initializeNew() {
var allAddress = document.getElementById("HiddenField1").value;
var testary = new Array();
testary = allAddress.split("|");
if (GBrowserIsCompatible()) {
//calls map to appear inside <div> with id, "map_canvas"
map = new GMap2(document.getElementById("map_canvas"));
//adds zoom and arrow controls to map
//map.addControl(new GSmallMapControl());
var marker = null;
var i = 0;
for (i = 0; i < testary.length; i++) {
address = testary[i];
geocoder = new GClientGeocoder();
//converts a street address into geocode for the api
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 13);
marker = new GMarker(point);
map.addOverlay(marker);
map.setMapType(G_HYBRID_MAP);
//adds your own marker title and description in html
marker.openInfoWindowHtml("<p class='para1bold' style=\"font-weight: bold;\">Address</p><p class='para1'>" + address + "</p>");
//Add click event on push pin to open info window on click of the icon
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("<p class='para1bold' style=\"font-weight: bold;\">Address</p><p class='para1'>" + address + "</p>");
});
//Provides map,satellite,hybrid and terrain views in the map along with zoom control
map.setUIToDefault();
}
}
)
}
}
}
I have stored address of group of items in an array and looped to display markers in the map. This displays only one marker for the last address present in the array. Please correct this code or provide new code to display multiple markers in Google map by providing address.
I ran into this exact same problem and fixed it. Look at the code that I have used. The specific bits are that marker needs to be an array and when you open the infowindow the content needs to be stored in the marker array. I would also suggest that you use something JSON instead which is easier to parse instead of separating with '|'.
try this: put var in front of marker
else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
map.setMapType(G_HYBRID_MAP);
//adds your own marker title and description in html
marker.openInfoWindowHtml("<p class='para1bold' style=\"font-weight: bold;\">Address</p><p class='para1'>" + address + "</p>");
//Add click event on push pin to open info window on click of the icon
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("<p class='para1bold' style=\"font-weight: bold;\">Address</p><p class='para1'>" + address + "</p>");
});
UPDATE
var geocoder = new GClientGeocoder();
var addresses = ["new york","chicago"];
var curIndex = 0;
function showAddress() {
var _cur = addresses[curIndex];
geocoder.getLatLng(
_cur,
function(point) {
if (!point) {
alert(_cur + " not found");
} else {
console.log(_cur+":"+point);
}
//do next after done
curIndex++;
if(curIndex<addresses.length)
showAddress();
}
);
}
showAddress();
</script>