I am using the following function with google maps API v3.
When a user drags and drop the map marker on a location then this location/address diplayed inside an input field.
How can i allow visitors typing their location inside this input field and then when they click on a button to move the marker to the desired location?
This is the javascript code:
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').value = str;
}
function initialize() {
var latLng = new google.maps.LatLng(34.02733457017991,-118.25942712402343);
map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom:8,
center: latLng,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: false,
streetViewControl: false,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Drag and Drop me anywhere',
map: map,
icon : 'markers/map_marker.png',
draggable: true
});
updateMarkerPosition(latLng);
geocodePosition(latLng);
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Locating...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
geocodePosition(marker.getPosition());
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
and this is the html code:
<body>
<div id="mapCanvas"></div>
<div id="infoPanel">
<div class="row"><span class="label">Lat, Lon:</span>
<span id="info"></span></div>
<div class="row"><span class="label">Address:</span>
<input class="address-field" id="address"/>
<button class="button-locate" id="locate">Locate</button></div>
</div>
</body>
"results" : [
{
"geometry" : {
"location" : {
"lat" : 37.4224764,
"lng" : -122.0842499
},
}
The result lat, lng of address Can you use this to set Location of marker, try this code;
var geocoder = new google.maps.Geocoder();
var marker;
function geocodePosition(pos) {
geocoder.geocode({
address: $("#idOfInput").val(),
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK){
map.setCenter(results[0].geometry.location);
marker.setPosition(results[0].geometry.location);
updateMarkerAddress(results[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
Related
I have an error that says
Uncaught TypeError: Cannot read property '__e3_' of null js?v=3.exp&key=AIzaSyDwehIgJvLsANnWEDppiUFr4Srk2G2M5IE&sensor=false&libraries=drawing,places:35
When I investigate, it takes me to this part of my code
google.maps.event.addListenerOnce(map, 'tilesloaded', function () {
Here is my code:
function initialize() {
var mzansi = new google.maps.LatLng(-28.2751829172523, 25.0430317799304);
var mapOptions = {
center: mzansi,
defaults: {
icon: 'red_dot.png',
shadow: 'dot_shadow.png',
editable: true,
strokeColor: '#990000',
fillColor: '#EEFFCC',
fillOpacity: 0.6
},
disableDefaultUI: true,
mapTypeControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT,
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
panControl: false,
streetViewControl: false,
zoom: 6,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP,
style: google.maps.ZoomControlStyle.SMALL
}
}
$('#tabNavigationDiv').tabs({
border: true,
onSelect: function (value) {
switch (value) {
case "Subscription List":
selectedDayTab = 1;
if (SubscriptionMap == null) {
SubscriptionMap = new google.maps.Map(document.getElementById('SubscriptionListMap'), mapOptions);
}
else {
google.maps.event.trigger(SubscriptionMap, 'resize');
}
break;
case "Predefined Location List":
selectedDayTab = 2;
if (PredefinedMap == null) {
PredefinedMap = new google.maps.Map(document.getElementById('PredefinedLocationListMap'), mapOptions);
}
else {
google.maps.event.trigger(PredefinedMap, 'resize');
}
break;
case "Predefined Location":
selectedDayTab = 3;
if (map == null) {
map = new google.maps.Map(document.getElementById('PredefinedLocationMap'), mapOptions);
}
else {
google.maps.event.trigger(map, 'resize');
}
break;
}
}
}).tabs('tabs');
google.maps.event.addListenerOnce(map, 'tilesloaded', function () {
RSABounds = map.getBounds();
console.log(RSABounds)
$(searchLocation).autocomplete({
source: function (request, response) {
if (geocoder == null) {
geocoder = new google.maps.Geocoder();
}
geocoder.geocode({
'address': request.term, bounds: RSABounds
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
/* map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});*/
map.setZoom(20);
var searchLoc = results[0].geometry.location;
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(lat, lng);
var bounds = results[0].geometry.bounds;
geocoder.geocode({
'latLng': latlng
}, function (results1, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
if (results1[1]) {
response($.map(results1, function (loc) {
return {
label: loc.formatted_address,
value: loc.formatted_address,
bounds: loc.geometry.bounds
}
}));
}
}
});
}
});
},
select: function (event, ui) {
var pos = ui.item.position;
var lct = ui.item.locType;
var bounds = ui.item.bounds;
if (bounds) {
map.fitBounds(bounds);
}
}
});
});
// searchBox = new google.maps.places.SearchBox(document.getElementById('description'));
searchBox = new google.maps.places.SearchBox(document.getElementById('searchLocation'));
google.maps.event.addListener(searchBox, 'places_changed', function () {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function (place) {
var marker = new google.maps.Marker({
position: place.geometry.location
});
var circle = new google.maps.Circle({
map: map,
radius: 16093, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function () {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}(place));
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(), 12));
});
google.maps.event.addListener(map, 'tilesloaded', function () {
});
map.drawingManager = new google.maps.drawing.DrawingManager({
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
/* google.maps.drawing.OverlayType.MARKER,
google.maps.drawing.OverlayType.POLYLINE,
google.maps.drawing.OverlayType.POLYGON,*/
google.maps.drawing.OverlayType.RECTANGLE
]
},
/* markerOptions: map.defaults,
polygonOptions: map.defaults,
polylineOptions: map.defaults,*/
rectangleOptions: map.defaults
});
map.drawingManager.setMap(map);
google.maps.event.addListener(map.drawingManager, 'overlaycomplete', function (event) {
var wkt;
//app.clearText();
clearMap();
arrayOverlays.push(event.overlay);
wkt = new Wkt.Wkt();
wkt.fromObject(event.overlay);
var myGeometry = wkt.write();
viewModel.location_geom(myGeometry);
// viewModel.radius(myGeometry);
console.log(myGeometry);
});
}
}
The map variable is not defined in your code unless you hit the switch case "Predefined Location". So except in that case it isn't defined (it will be null) in the line that generates the error:
google.maps.event.addListenerOnce(map, 'tilesloaded', function ()
I have a function to show a google map:
function initMapSA(lat, ln) {
var myLatLng = { lat: lat, lng: ln };
var opt = {
center: myLatLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
};
map2 = new google.maps.Map(document.getElementById('map_canvas_agent'), opt);
var markerSa = new google.maps.Marker({
position: myLatLng,
map: map2,
title: 'Hello World!'
});
}
In #modal-body I add <div id="map_canvas_agent"></div>
I trigger it via a form button click event:
$(".sa-location").click(function () {
var id = $("#ServiceAgent").val(); //combobox value
$.get("#Url.Action("GetServiceAgentLocation")", { id: id }, function (data) {
initMapSA(data.Lat, data.Ln);//Initialize google maps
}, "json");
});
The Goole Map is showing but it is just a grey screen rather than an actual map. How do I fix that?
Force trigger a resize on the map:
google.maps.event.trigger(map, 'resize');
I use Google Maps API for two things on my website:
First for displaying map:
jQuery(document).ready(function($) {
function initialize_business() {
var map_move = $(document).width() > 850 ? true : false;
var map_center = new google.maps.LatLng(parseFloat($('#business_sidebar_map').attr('data-lat')), parseFloat($('#business_sidebar_map').attr('data-lng')));
var map_options = {
zoom: 14,
center: map_center,
zoomControl: false,
scaleControl: false,
draggable: false,
scrollwheel: false,
mapTypeControl: false,
streetViewControl: false,
};
var map = new google.maps.Map(document.getElementById('business_sidebar_map'), map_options);
new google.maps.Marker({
position: map_center,
map: map,
icon: js_string.template_directory + '/images/marker.png'
});
}
google.maps.event.addDomListener(window, 'resize', initialize_business);
google.maps.event.addDomListener(window, 'load', initialize_business);
});
and for this map I need next api link:
<script src="https://maps.googleapis.com/maps/api/js"></script>
Secondly I use Google Map API for finding of GPS from my Address:
function google_geocoding() {
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('address'), {
types: ['geocode'],
componentRestrictions: {country: 'cz'},
});
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert('Bohužel jsme nanašli žádnou lokaci');
return;
}
document.getElementById('address_lat').value = place.geometry.location.lat();
document.getElementById('address_lng').value = place.geometry.location.lng();
});
}
and for this event I need next api link:
<script src="https://maps.googleapis.com/maps/api/js?libraries=places®ion=cz&callback=google_geocoding"></script>
In console I see next bug:
You have included the Google Maps API multiple times on this page.
So I probably need to combine Google script links to one, but I don't know how.
Thanks for help
I find solution:
Call google maps API once
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places®ion=cz">
Insted of callback param I simple Call the function so final script is:
jQuery(document).ready(function($) {
if($('#business_sidebar_map').length > 0) {
function initialize_business() {
var map_move = $(document).width() > 850 ? true : false;
var map_center = new google.maps.LatLng(parseFloat($('#business_sidebar_map').attr('data-lat')), parseFloat($('#business_sidebar_map').attr('data-lng')));
var map_options = {
zoom: 14,
center: map_center,
zoomControl: false,
scaleControl: false,
draggable: false,
scrollwheel: false,
mapTypeControl: false,
streetViewControl: false,
};
var map = new google.maps.Map(document.getElementById('business_sidebar_map'), map_options);
new google.maps.Marker({
position: map_center,
map: map,
icon: js_string.template_directory + '/images/marker.png'
});
}
google.maps.event.addDomListener(window, 'resize', initialize_business);
google.maps.event.addDomListener(window, 'load', initialize_business);
}
if($('#address').length > 0) {
function google_geocoding() {
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('address'), {
types: ['geocode'],
componentRestrictions: {country: 'cz'},
});
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert('Bohužel jsme nanašli žádnou lokaci');
return;
}
document.getElementById('address_lat').value = place.geometry.location.lat();
document.getElementById('address_lng').value = place.geometry.location.lng();
});
}
google_geocoding();
}
});
Using examples from Google's samples and other code found here on Stack Overflow, I've put together some JS that takes a street address and displays an overhead map as well as a Street View. For the most part these work wonderfully, but it breaks when the house is on a corner.
When the house is on a corner, it will sometimes show me the side of the house instead of the front of the house. If I go directly to Google Maps and search for that address, the Street View it shows is actually the front of the house, so I know there must be a way to determine the right view to use.
How do I get my code to show the front of the house like it does on Google's site?
function load_map_and_street_view_from_address(address) {
// Check if GPS has been locally cached.
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var gps = results[0].geometry.location;
create_map_and_streetview(gps.lat(), gps.lng(), 'map_canvas', 'pano');
}
});
}
function create_map_and_streetview(lat, lng, map_id, street_view_id) {
var panorama = new google.maps.StreetViewPanorama(document.getElementById(street_view_id));
var addLatLng = new google.maps.LatLng(lat,lng);
var service = new google.maps.StreetViewService();
service.getPanoramaByLocation(addLatLng, 50, function(panoData, status) {
if (status != google.maps.StreetViewStatus.OK) {
$('#pano').html('No StreetView Picture Available').attr('style', 'text-align:center;font-weight:bold').show();
return;
}
var angle = google.maps.geometry.spherical.computeHeading(panoData.location.latLng, addLatLng);
var panoOptions = {
position: addLatLng,
addressControl: false,
linksControl: false,
panControl: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
pov: {
heading: angle,
pitch: 0,
zoom: 1
},
enableCloseButton: false,
visible:true
};
panorama.setOptions(panoOptions);
});
var myOptions = {
zoom: 14,
center: addLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'transparent',
streetViewControl: false,
keyboardShortcuts: false
};
var map = new google.maps.Map(document.getElementById(map_id), myOptions);
var marker = new google.maps.Marker({
map:map,
animation: google.maps.Animation.DROP,
position: addLatLng
});
}
$(document).ready(function() {
console.log('ready');
load_map_and_street_view_from_address("2131 S SAN ANTONIO AVE, ONTARIO, CA 91762");
});
https://jsfiddle.net/kennywyland/xm59cbac/
You are setting the pano to the wrong position. You want it in front of the house (snap to road, use the directions service), but point it at the result of the geocoder.
updated fiddle
function create_map_and_streetview(addLatLng, panoLatLng, map_id, street_view_id) {
var panorama = new google.maps.StreetViewPanorama(document.getElementById(street_view_id));
var service = new google.maps.StreetViewService();
service.getPanoramaByLocation(panoLatLng, 50, function (panoData, status) {
if (status != google.maps.StreetViewStatus.OK) {
$('#pano').html('No StreetView Picture Available').attr('style', 'text-align:center;font-weight:bold').show();
return;
}
var angle = google.maps.geometry.spherical.computeHeading(panoData.location.latLng, addLatLng);
document.getElementById('angle').innerHTML = angle;
var panoOptions = {
position: panoLatLng,
pov: {
heading: angle,
pitch: 0,
zoom: 1
},
enableCloseButton: false,
visible: true
};
panorama.setOptions(panoOptions);
});
var myOptions = {
zoom: 16,
center: addLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'transparent',
streetViewControl: false,
keyboardShortcuts: false
};
var map = new google.maps.Map(document.getElementById(map_id), myOptions);
}
function load_map_and_street_view_from_address(address) {
// Check if GPS has been locally cached.
var geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var gps = results[0].geometry.location;
// create_map_and_streetview(gps.lat(), gps.lng(), 'map_canvas', 'pano');
var request = {
origin: address,
destination: address,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var cameraLatLng = response.routes[0].legs[0].steps[0].start_location;
create_map_and_streetview(gps, cameraLatLng, 'map_canvas', 'pano');
}
});
}
});
}
function create_map_and_streetview(addLatLng, panoLatLng, map_id, street_view_id) {
var panorama = new google.maps.StreetViewPanorama(document.getElementById(street_view_id));
var service = new google.maps.StreetViewService();
service.getPanoramaByLocation(panoLatLng, 50, function(panoData, status) {
if (status != google.maps.StreetViewStatus.OK) {
$('#pano').html('No StreetView Picture Available').attr('style', 'text-align:center;font-weight:bold').show();
return;
}
var marker = new google.maps.Marker({
map: map,
icon: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle_blue.png",
position: panoData.location.latLng
});
var angle = google.maps.geometry.spherical.computeHeading(panoData.location.latLng, addLatLng);
document.getElementById('angle').innerHTML = angle;
var panoOptions = {
position: panoLatLng,
pov: {
heading: angle,
pitch: 0,
zoom: 1
},
enableCloseButton: false,
visible: true
};
panorama.setOptions(panoOptions);
});
var myOptions = {
zoom: 16,
center: addLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'transparent',
streetViewControl: false,
keyboardShortcuts: false
};
var map = new google.maps.Map(document.getElementById(map_id), myOptions);
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
icon: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
position: addLatLng
});
}
$(document).ready(function() {
console.log('ready');
load_map_and_street_view_from_address("2131 S SAN ANTONIO AVE, ONTARIO, CA 91762");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?ext=.js"></script>
<div id="angle"></div>
<div id="map_canvas" style="width: 400px; height: 400px; border: 1px solid orange; display: inline-block;"></div>
<div id="pano" style="width: 400px; height: 400px; border: 1px solid green; display: inline-block;"></div>
I had created a gMap in javascript.
While loading the map, the marker also loads along with map.I want to load the marker after clicking the load marker button. How to do that?
JS:
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
}
});
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function initialize() {
var latLng = new google.maps.LatLng(-29.3456, 151.4346);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Position',
map: map,
draggable: true
});
updateMarkerPosition(latLng);
geocodePosition(latLng);
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerPosition(marker.getPosition());
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html:
<div id="info"></div>
<div id="mapCanvas"></div>
<button>Load MArker</button>
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
}
});
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function initialize() {
var latLng = new google.maps.LatLng(-29.3456, 151.4346);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Position',
map: null, //<-- it will be created but not shown.
draggable: true
});
updateMarkerPosition(latLng);
geocodePosition(latLng);
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerPosition(marker.getPosition());
});
$('button').click(function(){
marker.setMap(map); //<-- assign the map, in other words .. show it.
});
}
google.maps.event.addDomListener(window, 'load', initialize);
SECOND OPTION
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
}
});
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function initialize() {
var latLng = new google.maps.LatLng(-29.3456, 151.4346);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Position',
map: map,
draggable: true,
visible: false //<-- default value is true
});
updateMarkerPosition(latLng);
geocodePosition(latLng);
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerPosition(marker.getPosition());
});
$('button').click(function(){
marker.setVisible(true); //<-- show it.
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Check here for the difference of the two methods What is the difference between "marker.setVisible(false)" and "marker.setMap(null)" in Google Maps v3?