Google Maps Pass value of dragend to variable - google-maps-api-3

Ok I spent 2 days working on this time for some help :) Everything works fine with the code now I just need to make the marker draggable and update Lat and Lng values. At present the code captures lat and lng via current position as well as via entering a location on the web page. The value of _Lat and _lng are then submitted the a database. I need the user to be able to drag the marker to fine tune the location and update _lat and _lng prior to the database submit. I have made the marker draggable but I can't figure out how to add the dragend code so that it dynamically updates the value of lat and _lng prior to the database submit. I don't need to update anything on the web page just I need to update the _lat and _lng values that get posted to the database. Here is the existing code:
Thanks
var gmap;
var gmarker;
var geocoder;
function initialize() {
// Get here center of map - by default - San Francisco center
var center = new google.maps.LatLng(37.47, -122.25);
var mapOptions = {
center: center,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
geocoder = new google.maps.Geocoder()
gmap = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
// Set inner position of map to form parameters
$('input[name="_lat"]').val(37.47);
$('input[name="_lng"]').val(-122.25);
gmarker = new google.maps.Marker({
map: gmap,
position: center,
icon: '/static/internal/images/mapicon.png',
draggable: true
});
google.maps.event.addListener(gmap, 'click', function(event) {
gmarker.setPosition(event.latLng);
$('input[name="_lat"]').val(event.latLng.lat());
$('input[name="_lng"]').val(event.latLng.lng());
});
navigator.geolocation.getCurrentPosition(function(position){
var _lng = position.coords.longitude;
var _lat = position.coords.latitude;
$('input[name="_lng"]').val(_lng);
$('input[name="_lat"]').val(_lat);
var new_position = new google.maps.LatLng(_lat, _lng);
gmap.setCenter(new_position);
gmarker.setPosition(new_position);
})
}
function showAddress(address) {
if (geocoder) {
geocoder.geocode(
{'address': address},
function(results, status) {
if (status != google.maps.GeocoderStatus.OK) {
alert(address + " not found");
} else {
gmap.setCenter(results[0].geometry.location);
gmarker.setPosition(results[0].geometry.location);
$('input[name="_lat"]').val(results[0].geometry.location.lat());
$('input[name="_lng"]').val(results[0].geometry.location.lng());
}
}
);
}
}

listen to the position_changed-event of the marker:
google.maps.event.addListener(gmarker, 'position_changed', function() {
$('input[name="_lat"]').val(this.getPosition().lat());
$('input[name="_lng"]').val(this.getPosition().lng());
});

Your click event is on map it should be on marker
Change
google.maps.event.addListener(gmap, 'click', function(event) {
To
google.maps.event.addListener(gmarker, 'click', function(event) {

Related

How do I auto zoom to view multiple markers using the Google Geocoding API?

I'm using the Google Geocoding API to build a map that puts markers on whichever locations are requested. At the moment it auto-zooms to each location individually - how do I use fit Bounds to make it zoom to all the locations, i.e. if Sydney is input first, then London, how do I ask it to auto-zoom so the user can view both?
I'm very new to this so any advice welcome!
I've tried many different way to use bounds, fit Bounds, marker.length etc but none of it works or makes much sense to me.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 45.1497, lng: 100.0943},
zoom: 3
});
var geocoder = new google.maps.Geocoder()
var step1 = location.href.split("?")[1].split("=")[1]
$("#address1").val(step1);
geocodeAddress1(geocoder, map);
$(".steps").keypress(function() {
if (event.which == 13) {
geocodeAddress(geocoder, map);
}
})
};
var labelIndex = 0;
function geocodeAddress1(geocoder, resultsMap) {
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var address = $("#address1").val();
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
label: labels[labelIndex++ % labels.length],
position: results[0].geometry.location
});
} else {
alert('Search not successful: ' + status);
}
})
};
function geocodeAddress(geocoder, resultsMap) {
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var nextstep = "#".concat(event.target.id);
debugger;
var address = $(nextstep).val();
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
label: labels[labelIndex++ % labels.length],
position: results[0].geometry.location
});
} else {
alert('Search not successful: ' + status);
}
})
};
You need to store all the markers/loations first in an array each time you click "Geocode", then call bounds.extend() for each location searched to contain the given point and lastly call resultsMap.fitBounds() to set the viewport to contain the given bounds.
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
markerCount++;
markers[markerCount] = marker;
// extend the bounds here to consider each location
bounds.extend(results[0].geometry.location);
// then call fitBounts()
resultsMap.fitBounds(bounds);
Here's a working sample in JSFiddle.
Hope it helps!

Google map showing only some markers but all markers shown in debug mode

A few of my markers are not showing in the map I created and I have drilled down the reason being too many API calls. But the problem is that even after adding setTimout/ delay code all markers are not shown. When i debug the code in chrome though it works fine (even when i remove all the break points and allow the website to load - all markers are loaded without any issues)
www.khojiye.com is the link
function map_marker(ajax_result,address_length)
{
val = ajax_result[counter];
if($.trim(val)!=""){
//alert(i);
//alert(val);
var valA = val.split('###');
setTimeout(geocoder.geocode( { 'address': valA[0]}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK)
{
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
// Set the coordonates of the new point
var latLng = new google.maps.LatLng(lat, lng);
//bounds.extend(latLng);
var marker = new google.maps.Marker(
{
position: latLng,
map: map,
title: valA[0],
animation: google.maps.Animation.DROP,
icon:valA[1]
});
// The HTML that is shown in the window of each item (when the icon it's clicked)
var html = "<div style='width:150px; margin-top: -12px;'><h3 style='font-size:16px; font-weight:500;'>"+valA[2]+"</h3><h4 style='font-size:15px; line-height:21px;'>"+valA[0]+"</h4><a href='"+valA[3]+"'>View Detail</h4></div>";
// Binds the infoWindow to the point
bindInfoWindow(marker, map, infoWindow, html);
// Add the marker to the array
markers.push(marker);
counter++;
a_c++;
if(counter<address_length)
map_marker(ajax_result,address_length);
}
else{
//alert("Geocode was not successful for the following reason: " + status);
//marker = '';
//markers.push(marker);
//console.log(status);
counter++;
b_c++;
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT){
counter--;
console.log(counter);
delay=delay*5;
}
if(counter<address_length)
map_marker(ajax_result,address_length);
}
}),delay);
}
}
I dont know what i did is a hack or not:
1. it seems my use of set timeout was incorrect
2. I removed the setTimeout from top function and added it as
setTimeout(function() {map_marker(ajax_result,address_length);},delay);}

Google map API geolocation after first display of the map

This code takes a big list of (400) markers and adds it to the map, at the end, it shows the whole map including all the markers.
What I have tried to achieve is: when geolocation is available, center the map on location, zoom to level 16 and refresh the map to show it, otherwise, let the whole big map show... I have read and tried many different things, but the geolocation must happen before the map is created. I want to make it happen after. I show you my code here and the temporary link to the working site: http://studioteknik.co/brasseursillimites.com/detaillants/
function initialize()
{
var map = new google.maps.Map(document.getElementById('map-canvas'));
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (var i in locations) {
var p = locations[i];
var latlng = new google.maps.LatLng(p[1], p[2]);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: p[0]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.title);
infowindow.open(map, this);
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
Here is a simple example of geolocation. Just add the geolocation code anywhere after the map object is created. If the user doesn't allow geolocation, the map will be shown at the default location / zoom level.
function initialize() {
var mapOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(0,0)
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// Geolocation code
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
map.setZoom(16);
});
}
}
initialize();
JSFiddle demo

Count and output number of markers bound by circle radius

I have a map thats populated with markers of places from a fusion table. I'm taking the users location and displaying a circle of radius 10 miles from their location. Here is my code - http://connormccarra.com/sandbox/map/. How can I use the api to count the number of markers bound by the circle and output that number in the footer?
Cheers!
Relevant code:
var map;
function Initialize() {
var MapOptions = {
zoom: 7,
center: new google.maps.LatLng(53.4125694, -8.245014),
mapTypeId: google.maps.MapTypeId.ROADMAP,
sensor: true
};
map = new google.maps.Map(document.getElementById("map_canvas"), MapOptions);
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'Address',
from: '1OPU6utSjRYwJSFK-EXdaGmt2KgLTq2loVIjS3AA'
}
});
layer.setMap(map);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
map: map,
position: pos,
content: 'You are here!'
});
// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
map: map,
radius: 16093, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');
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 count = mgr.getMarkerCount(circle);
document.getElementById("Address").innerHTML += count + "<BR>";
google.maps.event.addDomListener(window, 'load', initialize);
//Maps API loaded, now load customizations
var element = document.createElement('script');
element.src = 'template.js';
element.type = 'text/javascript';
var scripts = document.getElementsByTagName('script')[0];
scripts.parentNode.insertBefore(element, scripts);
}
The markers created by a FusionTableLayer are not real markers, there is no way to get them as a kind of list to filter them(you can't get any details for the markers, except you click them).
But you may request the FusionTableAPI with a spatial condition(via AJAX, jsonp is supported).
The syntax for the query:
SELECT COUNT() from tableId
WHERE ST_INTERSECTS('Address',CIRCLE(LATLNG(lat,lng),10000))
How to send a query : https://developers.google.com/fusiontables/docs/v1/sql-reference
Demo(using data of another FusionTable because your table is protected):
http://jsfiddle.net/doktormolle/bAtgf/
Simplest way: use the geometry library computeDistanceBetween method. If the distance from the user's location is less than 10 miles, the marker is in the circle.
I suggest you first fetch all the coordinates of your FusionTablesLayer.
Here is an example which was used in the sidebar
http://www.geocodezip.com/v3_FusionTables_AfricaMap_kml_sidebar.html
Then using a loop statement you can use the computeDistanceBetween function.
Detect If Marker is Within Circle Overlay

API v3: Issue with GeoCoding service in Firefox 6.0 / IE 9.0

I have created a code to add multiple markers and infoWindows using the GeoCoding service. I have copied the method from API v3 Docs. My script pulls address information from a ASP.Net web service and writes them onto a hidden div element.
function codeAddress(address)
{
//Get the location information from address
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
//Add a google marker onto the given address
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
//Prepare a infoWindow to display complete address
var faddress = "<h4>Office Address:</h4><span>" + address + "</span>";
var infowindow = new google.maps.InfoWindow({content: faddress});
//Opening information window on mouseover event of marker
google.maps.event.addListener(marker, 'mouseover', function(){
infowindow.open(map, marker);
});
//closing the info window when mouse is moved out of marker
google.maps.event.addListener(marker, 'mouseout', function(){
infowindow.close();
});
}
});
}
Next piece of code reads the address from hidden div elements and adds the marker along with InfoWindows. This code works perfectly with Internet Explorer 7.0/8.0.
//Populate the result onto div element
$.each(arr,function(index, item){
$(".result").append("<div class='block'>" + item + "</div>");
});
//Loop through the div element and add marker to map
$(".block").each(function(){
codeAddress($(this).text());
})
But the same code is not working when i open it on Firefox 6.0/IE 9.0.
GeoCoding service returns ZERO_RESULTS for the same call. When I call the method 5 times with same address it is able to add markers.
Any idea if geoCoding service has issues with new browsers ?
Thanks in Advance...
Sudhir
this is the code im using to generate maps, you can take it and adjust it to your needs:
var address = document.getElementsByTagName('address')[0].innerHTML;
var title = document.getElementById('contact').getElementsByTagName('h2')[0].innerHTML;
var geocoder;
var map;
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 15,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: title
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});

Resources