Google maps API v3 markers - javascript

Can any one give me an idea on how to zoom your map according to the markers. Actually I have geocoded the addresses and the markers are shown on the map. But they are not centered i.e. I have to drag the map to see the other marker.I want my map to fit bounds using the addresses that I have in my addresses array. How this can be done.? My current code for geocoding is:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var addresses = new Array();
abc = document.getElementsByTagName('td');
//loc = mydiv.getAttribute("data-addr");
var l = abc.length;
for (var i=0; i < l; i++){
if (abc[i].hasAttribute('name'))
{
addresses.push(""+abc[i].innerHTML+""); //removed single quotes here. see previous code
}
}
var len = addresses.length;
var geocoder;
var map;
var add = document.getElementById("addr").value;
window.onload = function init() {
geocoder = new google.maps.Geocoder();
var add = document.getElementById("address").value;
var latlng = codeAddress(add);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
//for (var i = 0; i < addresses.length; i++)
//{
function codeAddress(add)
{
//var addr = addresses[i];
geocoder.geocode( { 'address':add }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function createMarkers()
{
for(var i = 0; i < len; i++){
(function(addresses){
geocoder.geocode( { 'address': addresses }, function(results) {
var marker = new google.maps.Marker ({
map: map,
position: results[0].geometry.location,//error:results[0] is undefined
title: address
});
google.maps.event.addListener(marker, 'click', function() {
alert(addresses);
});
});
})(addresses[i]);
}
}
window.onload = createMarkers;
</script>

In your function where you are creating the markers you can also extend the bounds (with
function createMarkers()
{
//create the bounds for the map
var bounds = new google.maps.LatLngBounds();
for(var i = 0; i < len; i++){
(function(addresses){
geocoder.geocode( { 'address': addresses }, function(results) {
var marker = new google.maps.Marker ({
map: map,
position: results[0].geometry.location,//error:results[0] is undefined
title: address
});
google.maps.event.addListener(marker, 'click', function() {
alert(addresses);
});
});
})(addresses[i]);
//extend the bounds with each address
bounds.extend (addresses[i]);
}
//fit to the full list of bounds
map.fitBounds(bounds);
}
If you want to set a maximum zoom level no matter what the actual bounds are you can add this after the map.fitBounds (you can change the level of zoom):
var listener = google.maps.event.addListener(map, "idle", function() {
if (map.getZoom() > 10) map.setZoom(10);
google.maps.event.removeListener(listener);
});

Related

Google Map API not plotting array of markers

I need some advice or a telling off because my code is wrong. I'm new to JQuery and google maps api. I have a JSON get to retrieve my data. I have declared an array and stored (hopefully this is the correct way to do this).
update** - Thanks to #geocodezip I have updated my code to allow correct population of array.
When I run my application the map loads fine but no markers.
I have changed my Google maps initializeMap() to the asynchronous version
function initializeMap() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
zoom: 12,
center: new google.maps.LatLng(citylat, citylng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < carparksArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(carparksArray[i][1], carparksArray[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(carparksArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
My array in console.log image
I now have an array populated, but still no markers on my map.
This is my whole script. Maybe there are some major flaws.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//define variables
var geocoder;
var citylat = 0;
var citylng = 0;
var carparksArray = [];
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position)
{
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction()
{
alert("Geocoder failed");
}
function initialize()
{
geocoder = new google.maps.Geocoder();
}
//get city of current location and runs codeAddress()
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({ latLng: latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
console.log(results);
$.each(arrAddress, function (i, address_component) {
if (address_component.types[0] == "postal_town") {
itemPostalTown = address_component.address_components[0].long_name;
document.getElementById("town").value = itemPostalTown;
codeAddress();
}
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
//get latlong of city and runs getCarParks()
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("town").value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
citylat = results[0].geometry.location.lat();
citylng = results[0].geometry.location.lng();
getCarParksLatLng();
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
//sets map up
function initializeMap() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
zoom: 12,
center: new google.maps.LatLng(citylat, citylng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < carparksArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(carparksArray[i][1], carparksArray[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(carparksArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
//loads map
function loadScript() {
var script = document.createElement("script");
script.src = "http://maps.googleapis.com/maps/api/js?callback=initializeMap";
document.body.appendChild(script);
}
//get carparks names
function getCarParksLatLng() {
var town = document.getElementById("town").value;
var carparkList = "<p>";
var uri = "http://localhost/api/carparks?$filter=Town%20eq%20%27" + town + "%27";
$.getJSON(uri,
function (data) {
carparksArray = [];
$('#here_data').empty(); // Clear existing text.
// Loop through the list of carparks.
$.each(data, function (key, val) {
carparksArray.push([val.Name, val.Latitude, val.Longitude]);
});
console.log(carparksArray);
});
loadScript();
}
$(document).ready(initialize)
</script>
You are not adding the entries to the carparkArray correctly. Each array element needs to be an array, so the array looks like this:
var carparksArray = [
['Bondi Beach', -33.890542, 151.274856, 4],
// ...
];
updated code:
var carparks = [];
$.getJSON(uri,
function (data) {
$('#here_data').empty(); // Clear existing text.
// Loop through the list of carparks.
$.each(data, function (key, val) {
carparks.push([val.Name, val.Latitude, val.Longitude]);
});
});
loadScript();
}
proof of concept fiddle
Thanks for everyone's help on this. Because #geocodezip stated that
$.getJSON is asynchronous I moved my loadscript() function call inside the getJSON function and it now plots the map points.
$.getJSON(uri,
function (data) {
carparksArray = [];
$('#here_data').empty(); // Clear existing text.
// Loop through the list of carparks.
$.each(data, function (key, val) {
carparksArray.push([val.Name, val.Latitude, val.Longitude]);
});
console.log(carparksArray);
loadScript();
});

Google Maps API Places Search get number of search results

I have implemented a sample using Places Search of Google Maps API. I would like to fetch the number of results I am fetching. New to Google Maps API. How do I achieve this?
jsFiddle
JS:
var map;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(19.107567, 72.8335);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 500,
types: ['hospital']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
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: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Replace your callback with this:
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// Just count the number of results passed to your callback
var numResults = results.length;
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}

Google Maps API v3

I am facing an issue with my google maps code. I am trying to place markers on my map from an array. But I am stuck in between when I am trying to do the same.My firebug console gives me an error that results is not defined in function createMarkers. Here is my code:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var addresses = new Array();
abc = document.getElementsByTagName('td');
//loc = mydiv.getAttribute("data-addr");
var l = abc.length;
for (var i=0; i < l; i++){
if (abc[i].hasAttribute('name'))
{
addresses.push("'"+abc[i].innerHTML+"'");
}
}
var len = addresses.length;
var geocoder;
var map;
var add = document.getElementById("addr").value;
window.onload = function init() {
geocoder = new google.maps.Geocoder();
var add = document.getElementById("address").value;
var latlng = codeAddress(add);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
//for (var i = 0; i < addresses.length; i++)
//{
function codeAddress(add)
{
//var addr = addresses[i];
geocoder.geocode( { 'address':add }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function createMarkers()
{
for(var i = 0; i < len; i++){
(function(addresses){
geocoder.geocode( { 'address': addresses }, function(results) {
var marker = new google.maps.Marker ({
map: map,
position: results[0].geometry.location,//error:results[0] is undefined
title: address
});
google.maps.event.addListener(marker, 'click', function() {
alert(addresses);
});
});
})(addresses[i]);
}
}
window.onload = createMarkers;
</script>
Well after a long battle with the code,I found the solution. The error I was facing because I was pushing the addresses into array in a wrong format i.e. I pushed the addresses into the array with a '(single quote) surrounding it,which the geocoder did not accept.So then finally edited the loc where I was pushing the address.The modified code is as :
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var addresses = new Array();
abc = document.getElementsByTagName('td');
//loc = mydiv.getAttribute("data-addr");
var l = abc.length;
for (var i=0; i < l; i++){
if (abc[i].hasAttribute('name'))
{
addresses.push(""+abc[i].innerHTML+""); //removed single quotes here. see previous code
}
}
var len = addresses.length;
var geocoder;
var map;
var add = document.getElementById("addr").value;
window.onload = function init() {
geocoder = new google.maps.Geocoder();
var add = document.getElementById("address").value;
var latlng = codeAddress(add);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
//for (var i = 0; i < addresses.length; i++)
//{
function codeAddress(add)
{
//var addr = addresses[i];
geocoder.geocode( { 'address':add }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function createMarkers()
{
for(var i = 0; i < len; i++){
(function(addresses){
geocoder.geocode( { 'address': addresses }, function(results) {
var marker = new google.maps.Marker ({
map: map,
position: results[0].geometry.location,//error:results[0] is undefined
title: address
});
google.maps.event.addListener(marker, 'click', function() {
alert(addresses);
});
});
})(addresses[i]);
}
}
window.onload = createMarkers;
</script>

how to get center latitude and longitude in route between two location

I am using google map to find route between two location.i want to get center latitude and longitude of the route. can u please tell me how to get center of the route.i am using the below code for getting routes,Thanks in advance
var map;
var directionsDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var infoWindow;
var service;
var lat1 = 0;
var lng1;
function pre_initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location.'
});
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var addressfrom = document.getElementById("from").value;
var addressto = document.getElementById("to").value;
var geocoder = new google.maps.Geocoder();
var coords = new google.maps.LatLng(0, 0);
alert(lat1);
coords = geocoder.geocode({ 'address': addressfrom }, function (results, status) {
results[0].geometry.location.lat();
results[0].geometry.location.lng();
});
directionsService = new google.maps.DirectionsService();
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)
// Instantiate an info window to hold step text.
infoWindow = new google.maps.InfoWindow();
stepDisplay = new google.maps.InfoWindow();
calcRoute();
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
radius: 100,
types: ['hospital', 'cafe', 'restaurant', 'food', 'bar'],
keyword: 'best view'
};
service = new google.maps.places.PlacesService(map);
//service.nearbySearch(request, callback);
service.radarSearch(request, callback);
//service.textSearch(request, callback);
}
function callback(results, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
for (var i = 0, result; result = results[i]; i++) {
createMarker(result);
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon:
{
// Star
path: 'M 0,-24 6,-7 24,-7 10,4 15,21 0,11 -15,21 -10,4 -24,-7 -6,-7 z',
fillColor: '#ff0000',
fillOpacity: 1,
scale: 1 / 4,
strokeColor: '#bd8d2c',
strokeWeight: 1
}
});
google.maps.event.addListener(marker, 'click', function () {
service.getDetails(place, function (result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
infoWindow.setContent(result.name);
infoWindow.open(map, marker);
});
});
}
function calcRoute() {
// First, remove any existing markers from the map.
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}
// Now, clear the array itself.
markerArray = [];
var start = document.getElementById('from').value;
var end = document.getElementById('to').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var warnings = document.getElementById('warnings_panel');
warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response);
}
});
}
function showSteps(directionResult) {
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_point,
map: map
});
attachInstructionText(marker, myRoute.steps[i].instructions);
markerArray[i] = marker;
}
}
function attachInstructionText(marker, text) {
google.maps.event.addListener(marker, 'click', function () {
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
</script>
Refer to the code below:
self.adjustPosition = function () {
var lat = 0, lng = 0;
if (self.nearbyPlaces().length == 0) {
return false;
}
for (var i = 0; i < self.nearbyPlaces().length; i++) {
lat += self.nearbyPlaces()[i].latitude;
lng += self.nearbyPlaces()[i].longitude;
}
lat = lat / self.nearbyPlaces().length;
lng = lng / self.nearbyPlaces().length;
self.map.setCenter(new window.google.maps.LatLng(lat, lng));
};

Google maps zoom level for country

I'm having a problem working out how to set the zoom level for different countries, I have managed to get the map working and displaying the country, just cannot seem to work out how to set the zoom level.
Any help would be appreciated.
Thanks
George
<script type="text/javascript">
var infowindow = null;
$(document).ready(function () { initialize(); });
function initialize() {
//var geocoder = new google.maps.Geocoder();
//geocoder.geocode({ 'address': address }, function (results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
// map.setCenter(results[0].geometry.location);
// map.fitBounds(results[0].geometry.viewport);
// }
//});
var centerMap = new google.maps.LatLng(#Html.Raw(#item.strLatLong));
var myOptions = {
zoom: 4, //<<-------How can I chnage this
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("WeatherMapLocation"), myOptions);
setMarkers(map, sites);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);
}
function setMarkers(map, markers) {
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,
title: sites[0],
zIndex: sites[3],
html: sites[4]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
</script>
From the documentation on the Geocoder, there is a viewport and a bounds returned in the geocoder's response which can be used to center and zoom the map on the result.
if (results && results[0] && results[0].geometry && results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
working example

Categories

Resources