I am quite a novice with javascript stuff and am currently faking it till i make it lol and now ive come across a small hill that i'm struggling to get over :S.
Currently my script finds the users location and adds a pin to the map while copying LatLon to some form fields.
In addition to just zooming in on the users location i would like them to have the ability to add a custom address which is entered into a text field, geocoded and then updates the current pin on the map.
This all works, although it adds an additional pin to the map rather than updating the current pin.
I am unsure how to pass the value from the address geocoding function back into the original pin / or do i delete the original pin and add a new pin. I'm sure i can reuse some functions as well... i don't think my code is terribly efficient :/
Any way i hope a guru out there can help me out
Cheers
Nick
var geocoder;
var map;
var pos;
function initialize() {
geocoder = new google.maps.Geocoder();
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var address = document.getElementById("address").value;
var initialLocation;
var myOptions = {
zoom: 12,
center: initialLocation,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
// 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,
title: 'Location found using HTML5.',
draggable: true
});
var lat = position.coords.latitude
var lng = position.coords.longitude
document.getElementById('geo_latitude').value=lat;
document.getElementById('geo_longitude').value=lng;
google.maps.event.addListener(marker, "dragend", function(event) {
var lat = event.latLng.lat()
var lng = event.latLng.lng()
var infowindow = new google.maps.InfoWindow({
content: '<b><?php _e('Latitude:');?></b>' + lat + '<br><b><?php _e('Longitude:');?></b>' + lng
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, "dragstart", function() {
infowindow.close();
});
document.getElementById('geo_latitude').value=lat;
document.getElementById('geo_longitude').value=lng;
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else if (google.gears) {
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeoLocation(browserSupportFlag);
});
// Browser doesn't support Geolocation
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag == true) {
alert("Geolocation service failed.");
initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in New York.");
initialLocation = newyork;
}
map.setCenter(initialLocation);
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
//-------------------------------------------------------End initialize
function findAddress(address) {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var pos = results[0].geometry.location;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
To 'move' your existing marker, you'll wanna make sure its global and then you can just update its position within the findAddress function with something like:
marker.setPosition(results[0].geometry.location);
Related
I have an array with location data with one of the items being an address - ie. "123 Main Street, San Francisco, California". I want to take that address, turn it into coordinates, then use those coordinates to plot a marker on the map. To do this, I know I need to use geocode(), so I added that part into my loop.
If I were to use latitude and longitude in my array instead of the address, I can get this to work fine. But, since I added geocode() into my loop, I can only get the first location in the array to display a marker.
I have seen some similar questions on here that suggest using callback() but I did not understand it. I've also seen a suggestion to add a delay to geocode() of 0.5 seconds which worked for the poster, but comments said it may not load all locations on slower internet speeds.
How can I fix this to show all locations in the correct way?
// Create the map with markers.
function createmap(zoomlevel, centerpos, showDot)
{
// Create the map canvas with options.
var map = new google.maps.Map(document.getElementById('map-canvas'), {
scrollwheel: false,
draggable: true,
mapTypeControl: false,
zoom: zoomlevel,
center: new google.maps.LatLng(40.577453, 2.237408), // Center the map at this location.
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
// For each location in the array...
for (i = 0; i < locations.length; i++)
{
// Get the coordintes for the address.
var geocoder = new google.maps.Geocoder();
var address = locations[i][5]; // ***This variable will output the address.***
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location_latitude = results[0].geometry.location.lat();
var location_longitude = results[0].geometry.location.lng();
// Create the map marker icon (SVG file).
var marker_icon = {
url: '//'+domain+'/__NEW__/_backend/assets/img/map-marker.svg',
anchor: new google.maps.Point(25,50),
scaledSize: new google.maps.Size(50,50)
}
// Place the marker on the map.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location_latitude, location_longitude),
map: map,
icon: marker_icon
});
}
});
}
}
This is how I am placing map markers on Google Maps:
<script type="text/javascript">
let map;
let parameters;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: #Model.Latitude , lng: #Model.Longitude },
zoom: #Model.Zoom,
});
#foreach (var asset in dbService.Assets)
{
#if (asset.State != Models.AssetState.deleted)
{
#:parameters = 'Id = #asset.Id\n' + 'Temperature = #asset.Temperature\n' + 'Moisture = #asset.Moisture\n';
#:setMarker('#asset.Latitude', '#asset.Longitude', '#asset.State');
}
}
}
function getIconByState(state) {
if (state == 'non_functional') {
return 'non-functional.png';
}
else if (state == 'under_maintenance') {
return 'under-maintenance.png';
}
else if (state == 'functional') {
return 'functional.png';
}
}
function setMarker(lat, lng, state) {
var markerjs = new google.maps.Marker({
icon: getIconByState(state),
position: new google.maps.LatLng(lat, lng),
});
markerjs.setMap(map);
let infowindow = new google.maps.InfoWindow({
content: parameters,
});
markerjs.addListener("click", () => {
infowindow.open(map, markerjs);
});
}
</script>
//this is how to use the callback
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap&libraries=&v=weekly"
defer></script>
In this code, I use the latitude and longitude to place a marker on the Map.
If you want to extract the latitude and longitude from an address, then use geocoder API in the following way:
<script type="text/javascript">
function setCoordinates() {
let address = document.getElementById('zip').value;
if (address) {
let geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('latitude').value = results[0].geometry.location.lat();
document.getElementById('longitude').value = results[0].geometry.location.lng();
}
else {
console.log('geocoding failed');
}
});
}
}
else {
alert('Please enter postal code to use this functionality');
}
}
</script>
I have a nearby search map, in every open of this map page, it returns the current position, now When I get the current position by coordinates, I want to reverse geocode it into an address name, the problem is I modified my code from this source: https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/geocoding-reverse
with
<script>
function getPosition() {
navigator.geolocation.getCurrentPosition(position => {
currentLatLon = [position.coords.latitude, position.coords.longitude];
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(
document.getElementById('map'), {
center: new google.maps.LatLng(...currentLatLon),
zoom: 20
});
var geocoder = new google.maps.Geocoder();
service = new google.maps.places.PlacesService(map);
document.getElementById("curr").innerHTML=currentLatLon;
document.getElementById("address").value=currentLatLon;
geocodeLatLng(geocoder,map,infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('curr').value;
var latlngStr = input.split(',');
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
</script>
this should return the place name in the map which is like the source code I copied from above
https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/geocoding-reverse, what could be wrong in my modification? I have an error in the console when I run my modified code, error in the console
Here's my full code without the api key: https://pastebin.com/BhEqRsq0
You set the lat/lng coordinates to the <p> element's innerHTML, not to its (unsupported) value which is why it returns undefined:
document.getElementById("curr").innerHTML = currentLatLon;
So change this code:
var input = document.getElementById('curr').value;
to the following:
var input = document.getElementById('curr').innerHTML;
I just ran your web app on my end and reverse geocoding works fine after the above fix. So hope this helps!
I can create a webpage that takes the name, address, lat and long of many businesses in a specific city and have put them into an embedded google map on my page. The connection to the database works, putting up the markers on the map works, however what I can't figure out from any examples, including those on Googles developers page, is how to user a user's location instead of the default coord in the googlemap.js file. What am I missing here?
var map;
var geocoder;
function loadMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'),
{
zoom: 14,
center: pos
});
});
}
var marker = new google.maps.Marker({
// position: pune,
map: map
});
var cdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
codeAddress(cdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
showAllHonda(allData)
}
function showAllHonda(allData) {
var infoWind = new google.maps.InfoWindow;
Array.prototype.forEach.call(allData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = data.name;
content.appendChild(strong);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map
});
marker.addListener('click', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
})
})
}
function codeAddress(cdata) {
Array.prototype.forEach.call(cdata, function(data){
var address = data.name + ' ' + data.address;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
var points = {};
points.id = data.id;
points.lat = map.getCenter().lat();
points.lng = map.getCenter().lng();
updateHondaWithLatLng(points);
} else {
alert('Geocode was not successful for the following reason: ' + status)
}
});
});
}
To find user's position you can use navigator.geolocation :
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'),
{
zoom: 14,
center: pos
});
});
}
I try to get back the adress of the point where the "user" clicks on the "google map" I have implemented on my website.
I copied the source code form developers.google.com and made a view adaptations. In the source from google, you get the "latlng" by an input field. I get it by a "event".
In my "geocode-function" I sum my "lat" and "lng" parameters together to what they would have looked like if they came out of the input field.
Here is the code:
// Set variables
var clicklat;
var clicklng;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow;
// Listen for click on map
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
clicklat = parseFloat(event.latLng.lat());
clicklng = parseFloat(event.latLng.lng());
geocodeLatLng(geocoder, map, infowindow);
});
// Geocode function
function geocodeLatLng(geocoder, map, infowindow) {
var input = "#{clicklat},#{clicklng}"
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[1]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
Now, the problem I have is that console.log(input); gives back: #{clicklat},#{clicklng}. Why, the heck, my variables get not implemented there?
It looks like you are trying to usea "jade" and is not working?
Anyway Here is a way to make it work:
// Set variables
//var clicklat;
//var clicklng;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow;
// Listen for click on map
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
//clicklat = parseFloat(event.latLng.lat());
//clicklng = parseFloat(event.latLng.lng());
geocodeLatLng(geocoder, map, infowindow, event.latLng); //I add this as a parameter
});
// Geocode function
function geocodeLatLng(geocoder, map, infowindow, thelocation) {
// var input = "#{clicklat},#{clicklng}"
// var latlngStr = input.split(',', 2);
// var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': thelocation}, function(results, status) {
if (status === 'OK') {
if (results[1]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: results[1].geometry.location,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
My code works fine in firefox but not word in chrome(chrome doesn't show google map):
http://www.khadamatchi.com/frontend/Index/addAddressByUser
my codes:
getLocation();
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
getAddress(lat,lng);
initialize(lat,lng);
}
//START FIND LOCATION
var geocoder = new google.maps.Geocoder();
var marker = null;
var map = null;
function initialize(lat,lng) {
//var $latitude = document.getElementById('latitude');
// var $longitude = document.getElementById('longitude');
var latitude = lat;
var longitude = lng;
var zoom = 16;
var LatLng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: zoom,
center: LatLng,
panControl: false,
zoomControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
if (marker && marker.getMap) marker.setMap(map);
marker = new google.maps.Marker({
position: LatLng,
map: map,
title: 'Drag Me!',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function(marker) {
var latLng = marker.latLng;
// $latitude.value = latLng.lat();
// $longitude.value = latLng.lng();
//console.log( );
getAddress(latLng.lat(),latLng.lng());
});
}
// initialize();
$('#findbutton').click(function (e) {
var address = $("#Postcode").val();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker.setPosition(results[0].geometry.location);
$(latitude).val(marker.getPosition().lat());
$(longitude).val(marker.getPosition().lng());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
e.preventDefault();
});
function getAddress(lat,lon)
{
//http://maps.googleapis.com/maps/api/geocode/json?latlng=35.706172,51.316568&sensor=true&language=fa
$.ajax({
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat +","+lon + "&sensor=true&language=fa",
success: function(response) {
//Do Something
console.log(response);
var address_components = response.results[0].formatted_address;
$('#address').val(address_components);
},
error: function(xhr) {
//Do Something to handle error
}
});
}
You have two errors here, you are trying to execute some jQuery related code before you download jQuery, resulting in error;
Uncaught ReferenceError: $ is not defined
Example on line 172 $(document).ready(function
Also you are trying to execute some code to the google maps before it is loaded, row 632 var geocoder = new google.maps.Geocoder();
Resulting in error Uncaught ReferenceError: google is not defined
You can move the geocoder inside the initalize function you have or remove the async defer from the <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCfbbmUkl56UuSeZ5nSOwsKTNxplmnheuU&callback=initialize&language=fa" async defer></script>
You also define function initialize twice in the source code, this might bring you some weird issues in the future, each function name should be unique and descriptive about what they do.
UPDATE
For the comment, as you removed the async defer from the google maps loading, can you also remove the &callback=initialize from the src url.
UPDATE 2
Now we've gotten rid of the errors, now there is something weird going on in the function initialize
function initialize()
{
var tehran=new google.maps.LatLng(35.6961111,51.4230556);
var mapProp = {
center:tehran,
zoom:13,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var myCity = new google.maps.Circle({
center:tehran,
radius:3000,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4
});
myCity.setMap(map);
}
This does not work, if you replace this with;
function initMap()
{
map = new google.maps.Map(document.getElementById('googleMap'), {
center: {lat: 35.6961111, lng: 51.4230556},
zoom: 13
});
}
initMap();
The map will display correctly, then you can later focus on customising the styles of the map.