Plot multiple points on google map using API - google-maps

I am trying to show different points on any route on google map using the API. I want to pass in starting, stopping and finishing locations. Is this possible using the javascript API or would I need to look into other options such as geolocation?
I am using the following code to achieve this:
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.(-64.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=52554&sensor=false&callback=initialize";
document.body.appendChild(script);
}

Here is my code.
`<script type="text/javascript">
var geocoder = null;
var arr = new Array();
var arr1 = new Array();
var arr2 = new Array();
var map = null;
var chr;
var baseIcon = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng('<%=Request["Lat"]%>', '<%=Request["Long"]%>'), 13);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
baseIcon = new GIcon();
// baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(25, 30);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);
// Creates a marker whose info window displays the letter corresponding to the given index.
function createMarker(point, index) {
// Create a lettered icon for this point using our icon class
var letter = String.fromCharCode("A".charCodeAt(0) + index);
var letteredIcon = new GIcon(baseIcon);
letteredIcon.image = "markers/marker" + index + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon: letteredIcon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function () {
marker.openInfoWindowHtml("<table><tr><td><img src=markers/marker" + index + ".png length=25 width=25 /></td>" + "<td>" + arr2[index] + "</td></tr></table>");
});
return marker;
}
for (var i = 0; i < arr.length; i++) {
var latlng = new GLatLng(arr[i], arr1[i]);
map.addOverlay(createMarker(latlng, i));
}
}
}
`

Related

google maps onclick go to marker on map

I'm having issues trying to get my map to go to the marker of a location when a "View on Map" link is clicked. I keep getting the error "TypeError: map.setOptions is not a function".
Here's the code:
var infowindow = null;
function initialize(){
var myOptions = {
zoom:3,
center:new google.maps.LatLng(0,0),
mapTypeId:google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(
document.getElementById('map'),myOptions);
setMarkers(map,sites);
}
var infowindow = new google.maps.InfoWindow({
content:'Loading...'
});
var sites = [
['GIC Campers Sydney',-33.935477,151.012108,1,'xxx'],
['GIC Campers Brisbane',-27.5445735,153.0139405,1,'yyy'],
['GIC Campers Melbourne',-37.650735,144.940551,1,'zzz']
];
function setMarkers(map,markers){
var bounds = new google.maps.LatLngBounds();
var image = new google.maps.MarkerImage('/templates/home/images/google-pin.png',
new google.maps.Size(60,60),
new google.maps.Point(0,0),
new google.maps.Point(30,60));
for(var i=0;i<markers.length;i++){
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1],sites[2]);
var marker = new google.maps.Marker({
position:siteLatLng,
map:map,
icon:image,
title:sites[0],
zIndex:sites[3],
html:sites[4]
});
google.maps.event.addListener(marker,'click',function(){
map.setZoom(15);
map.setCenter(marker.getPosition());
infowindow.setContent(this.html);
infowindow.open(map,this);
});
bounds.extend(siteLatLng);
map.fitBounds(bounds);
}
};
function loadcity(which){
initialize();
if(which == 'gic-campers-sydney'){
var newPos = new google.maps.LatLng(-33.935477,151.012108);
map.setOptions({center:newPos,zoom:15});
}
if(which == 'gic-campers-brisbane'){
var newPos = new google.maps.LatLng(-27.5445735,153.0139405);
map.setOptions({center:newPos,zoom:15});
}
if(which == 'gic-campers-melbourne'){
var newPos = new google.maps.LatLng(-37.650735,144.940551);
map.setOptions({center:newPos,zoom:15});
}
}
jQuery(document).ready(function(e) {
initialize();
jQuery('.updatemap').click(function(e){
e.preventDefault();
});
});
and an example link:
<a onclick="loadcity('gic-campers-brisbane');" class="updatemap" href="#gic-campers-brisbane">View on map</a>
Any help on this would be greatly appreciated.
Your map variable is local to the initialize function. It is not available inside the loadcity function.
One fix is to make it global (like your infowindow):
var infowindow = null;
var map = null;
function initialize(){
var myOptions = {
zoom:3,
center:new google.maps.LatLng(0,0),
mapTypeId:google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(
document.getElementById('map'),myOptions);
setMarkers(map,sites);
}
Not sure why you recreate the map (call initialize() every time loadcity runs), you really should only need to do that once.

trouble with fusion table map, custom marker and infowindow

I have been working on a fusion table map. I am trying to add custom markers and infowindows but I am having issues getting it to show my markers and infowindows. I think I have something out of order or maybe a few syntax errors I am unable to find. I have sort of confused myself up a bit on the process. I would appreciate any help.
var tableId ="1zFwXiOkWbKCY9xRGvXBdHjUkTsirnwbr77WjTds"; // original table
google.load('visualization', '1');
var map;
var markers = [];
var infoWindow = new google.maps.InfoWindow();
function initialize() {
var ak = new google.maps.LatLng(64.958056,-147.618333);
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: ak,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var queryStr = "SELECT name, lat, lng, description FROM "+tableId+" ORDER BY name";
document.getElementById('info').innerHTML += queryStr +"<br>";
var queryText = encodeURIComponent(queryStr);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
query.send(getData);
}
function getData(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var dt = response.getDataTable();
document.getElementById('info').innerHTML += "rows="+dt.getNumberOfRows()+"<br>";
for (var i = 0; i < dt.getNumberOfRows(); i++) {
var lat = dt.getValue(i,1);
var lng = dt.getValue(i,2);
var name = dt.getValue(i,0);
var description = dt.getValue(i,3);
}
var pt = new google.maps.LatLng(lat, lng);
var html = "<span style='font-size:13px;font-weight:bold;color:#236192;'>" + name + "</span><p style='font-size:12px;'>" + description + "</p>";
var info = html;
}
function createMarker(pt,info) {
var iconURL = 'uaf-icon.png';
var iconSize = new google.maps.Size(29,60);
var iconOrigin = new google.maps.Point(0,0);
var iconAnchor = new google.maps.Point(15,60);
var myIcon = new google.maps.MarkerImage(iconURL, iconSize, iconOrigin, iconAnchor);
var shadowURL = 'uaf-shadow.png';
var shadowSize = new google.maps.Size(63, 60);
var shadowOrigin = new google.maps.Point(0, 0);
var shadowAnchor = new google.maps.Point(15, 60);
var myShadow = new google.maps.MarkerImage(shadowURL, shadowSize, shadowOrigin, shadowAnchor);
var iconShape = [18,0,20,1,22,2,23,3,24,4,25,5,26,6,27,7,27,8,28,9,28,10,28,11,28,12,28,13,28,14,28,15,28,16,28,17,28,18,28,19,27,20,27,21,26,22,26,23,25,24,24,25,23,26,21,27,20,28,16,29,21,31,21,32,21,33,21,34,21,35,20,36,20,37,20,38,19,39,19,40,19,41,18,42,18,43,18,44,18,45,17,46,17,47,17,48,17,49,16,50,16,51,16,52,15,53,15,54,15,55,14,56,14,57,14,58,14,59,13,59,13,58,13,57,13,56,12,55,12,54,12,53,12,52,11,51,11,50,11,49,11,48,11,47,10,46,10,45,10,44,10,43,9,42,9,41,9,40,9,39,9,38,8,37,8,36,8,35,8,34,8,33,7,32,7,31,12,29,9,28,7,27,6,26,4,25,3,24,3,23,2,22,1,21,1,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,1,9,1,8,2,7,2,6,3,5,4,4,5,3,6,2,8,1,10,0,18,0];
var myMarkerShape = {
coord: iconShape,
type: 'poly'
};
var myMarkerOpts = {
position: point,
map: map,
icon: myIcon,
shadow: myShadow,
shape: myMarkerShape
};
var marker = new google.maps.Marker(myMarkerOpts);
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.close();
infoWindow.setContent(info);
infoWindow.open(map,marker);
});
}
function myclick(num) {
google.maps.event.trigger(markers[num], "click");
}
first get the map displaying with default markers. You aren't calling the createMarker function (or creating any markers):
for (var i = 0; i < dt.getNumberOfRows(); i++) {
var lat = dt.getValue(i,1);
var lng = dt.getValue(i,2);
var name = dt.getValue(i,0);
var description = dt.getValue(i,3);
var pt = new google.maps.LatLng(lat, lng);
createMarker(pt,"<b>"+name+"</b><br>"+description);
}
there is a typo in createMarker (there is no "point" variable in the scope of the function, it should be "pt"), look for and address any errors in the javascript console.
function createMarker(pt,info) {
var iconURL = 'uaf-icon.png';
var iconSize = new google.maps.Size(29,60);
var iconOrigin = new google.maps.Point(0,0);
var iconAnchor = new google.maps.Point(15,60);
var myIcon = new google.maps.MarkerImage(iconURL, iconSize, iconOrigin, iconAnchor);
var shadowURL = 'uaf-shadow.png';
var shadowSize = new google.maps.Size(63, 60);
var shadowOrigin = new google.maps.Point(0, 0);
var shadowAnchor = new google.maps.Point(15, 60);
var myShadow = new google.maps.MarkerImage(shadowURL, shadowSize, shadowOrigin, shadowAnchor);
var iconShape = [18,0,20,1,22,2,23,3,24,4,25,5,26,6,27,7,27,8,28,9,28,10,28,11,28,12,28,13,28,14,28,15,28,16,28,17,28,18,28,19,27,20,27,21,26,22,26,23,25,24,24,25,23,26,21,27,20,28,16,29,21,31,21,32,21,33,21,34,21,35,20,36,20,37,20,38,19,39,19,40,19,41,18,42,18,43,18,44,18,45,17,46,17,47,17,48,17,49,16,50,16,51,16,52,15,53,15,54,15,55,14,56,14,57,14,58,14,59,13,59,13,58,13,57,13,56,12,55,12,54,12,53,12,52,11,51,11,50,11,49,11,48,11,47,10,46,10,45,10,44,10,43,9,42,9,41,9,40,9,39,9,38,8,37,8,36,8,35,8,34,8,33,7,32,7,31,12,29,9,28,7,27,6,26,4,25,3,24,3,23,2,22,1,21,1,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,1,9,1,8,2,7,2,6,3,5,4,4,5,3,6,2,8,1,10,0,18,0];
var myMarkerShape = {
coord: iconShape,
type: 'poly'
};
var myMarkerOpts = {
position: pt,
map: map,
icon: myIcon,
shadow: myShadow,
shape: myMarkerShape */
};
var marker = new google.maps.Marker(myMarkerOpts);
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.close();
infoWindow.setContent(info);
infoWindow.open(map,marker);
});
}
working example (with default icons)

Google Maps Api V3 Zoom links in infowindow not working

I am building a store locator using php sql and javascript. I've done this tutorial https://developers.google.com/maps/articles/phpsqlsearch_v3 and got it working. I am trying to implement zoom in/out links on the infoWindows, for when the user clicks a marker. Its not working, in FireFox I am getting no errors in the console. In Chrome I am getting Uncaught TypeError: Object # has no method 'setCenter'
Ive been searching the forums but have been unable to find a solution. Sorry I dont have a version online to look at, working locally. Below is the script I am using.
var map = null;
var markers = [];
var infoWindow;
var locationSelect;
//On page load Create a google map in #map
//Set default cordinates & Map style to roadmap
function load() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(43.907787,-79.359741),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
infoWindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50)
});
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none") {
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}
//Search for LAT/LNG of a place using its address using Google Maps Geocoder
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
//Clears Prve location, in info box
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
}
//Look for locations near by and loop through all data getting lat & lng of each marker
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'http://localhost:8888/starward/wp-content/themes/starward/map_request.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var zoom = 18;
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address,zoom);
bounds.extend(latlng);
}
map.fitBounds(bounds);
map.setZoom(11);
// map.setCenter(center);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
//Creates marker on the map
//Adds event for user when they click address info pops up
function createMarker(latlng, name, address, zoom) {
//var html = "<b>" + name + "</b> <br/>" + address
// add the zoom links
var html = "<b>" + name + "</b> <br/>" + address
html += '<br>Zoom To';
html += ' [+]';
html += ' [-]';
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
marker.MyZoom = zoom;
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);
}
//Look up XML sheet to get data
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
It works for me in both IE and Firefox. Although to me the behavior makes more sense if I set the center for the "ZoomTo" link as well:
html += '<br>Zoom To';

Markers render more than once

i've implemented google maps v3, it updates while bounds_changed event but the problem is when the event triggers it renders the markers more than once, any suggestions.
i've added the makers to marker manager.
var map = null;
var myLatLng = null;
var sidebarHtml = "";
var infowindow = infowindow = new google.maps.InfoWindow({});;
var mgr = null;
var currentBounds = null;
var xml = null;
var markers = null;
var markersArray = [];
var customIcons = {
restaurant: {
icon: 'images/icon_01.png'
},
bar: {
icon: 'images/icon_02.png'
}
}
function load() {
var myOptions = ({
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
mgr = new MarkerManager(map, {fitBounds: true});
google.maps.event.addListener(map, 'bounds_changed', downloadUrl);
}
function downloadUrl() {
var request = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest;
var params = "";
var url = "phpmysqlajax_genxml.php";
request.onreadystatechange = function() {
if(request.readyState == 4) {
//alert(request.responseXML);
useTheData(request);
}
};
request.open("GET", url + params, true);
request.send(null);
}
function useTheData(data) {
currentBounds = map.getBounds();
xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
mgr.clearMarkers();
if (!currentBounds) currentBounds = new google.maps.LatLngBounds();
sidebarHtml = '<ul class="sidebar">';
for(var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var type = markers[i].getAttribute("type");
var latlng = new google.maps.LatLng(lat, lng);
if (currentBounds.contains(latlng)) {
attachMarker( name, address, latlng, type );
markerSidebarEntry(i);
}
}
sidebarHtml += "</ul>";
document.getElementById("sidebar").innerHTML = sidebarHtml;
};
function attachMarker( name, address, latlng, type ) {
var marker = new google.maps.Marker({
position : latlng,
map: map,
icon : customIcons[type].icon
});
mgr.addMarker(marker, 5);
markersArray.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent( address );
infowindow.open(map, this);
});
// add marker here.
}
function markerSidebarEntry(i) {
var name = markers[i].getAttribute("name");
sidebarHtml += '<li class="' + markers[i].getAttribute("type") + '">' + name + '</li>';
}
function markerClick(i) {
google.maps.event.trigger(markersArray[i], "click");
}
It may just be a copy-paste error, but this code doesn't seem correct (double-declaration of 'infowindow' and duplicated ; at the end):
var infowindow = infowindow = new google.maps.InfoWindow({});;
Also here you don't need the () surrounding the {}
var myOptions = ({
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
Suggest you run your JS code through something like JSLint.

How to get the Google Map based on Latitude on Longitude?

I want to display Google map in my web page based on longitude and latitude. First user want to enter longitude and latitude in two text box's. Then click submit button I have to display appropriate location in Google map.And also I want to show the weather report on it.How to do that? Thank You.
Create a URI like this one:
https://maps.google.com/?q=[lat],[long]
For example:
https://maps.google.com/?q=-37.866963,144.980615
or, if you are using the javascript API
map.setCenter(new GLatLng(0,0))
This, and other helpful info comes from here:
https://developers.google.com/maps/documentation/javascript/reference/?csw=1#Map
this is the javascript to display google map by passing your longitude and latitude.
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
Have you gone through google's geocoding api. The following link shall help you get started:
http://code.google.com/apis/maps/documentation/geocoding/#GeocodingRequests
Firstly add a div with id.
<div id="my_map_add" style="width:100%;height:300px;"></div>
<script type="text/javascript">
function my_map_add() {
var myMapCenter = new google.maps.LatLng(28.5383866, 77.34916609);
var myMapProp = {center:myMapCenter, zoom:12, scrollwheel:false, draggable:false, mapTypeId:google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("my_map_add"),myMapProp);
var marker = new google.maps.Marker({position:myMapCenter});
marker.setMap(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_key&callback=my_map_add"></script>
<script>
function initMap() {
//echo hiii;
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(8.5241, 76.9366),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('package');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
// var name = markerElem.getAttribute('name');
// var address = markerElem.getAttribute('address');
// var type = markerElem.getAttribute('type');
// var latitude = results[0].geometry.location.lat();
// var longitude = results[0].geometry.location.lng();
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('latitude')),
parseFloat(markerElem.getAttribute('longitude'))
);
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var package = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
package.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, package);
});
});
});
}
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);
}