Firstly, I have been checking all over the web but I couldnt find an answer.
I combined autocomplete with goole maps and if a user wants, he/she can move the marker as well and I get address from it. You can find the code below.
When a user searches for instance Nice, France, is it possible to fit Nice from e.g borders to my map? Maybe I have to change the zoom dynamically or I need to set new viewport, I am not sure. So far what I found is, I can give a distance and create a circle to fit that circle to the viewport. But circle's radius is set, so it can fit to Nice but can not fit to Miami.
Hope I could explain what I mean. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#map_canvas {
width: 980px;
height: 500px;
}
#current {
padding-top: 5px;
}
</style>
</head>
<body>
<label>Enter address:</label><br>
<input id="searchTextField" type="text" size="50" style="margin-bottom: 20px;">
<section>
<div id='map_canvas' style=""></div>
<div id="current">No info...</div>
</section>
<div style="margin-top: 10px;" id="data_area">
</div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(41.0082, 28.9784),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(41.0082, 28.9784),
draggable: true
});
var geocoder = new google.maps.Geocoder;
var markers = [];
markers.push(myMarker);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
map.addListener('idle', function() {
console.log(map.getBounds());
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var place = autocomplete.getPlace();
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng()),
draggable: true
});
markers.push(myMarker);
map.setCenter(myMarker.position);
myMarker.setMap(map);
google.maps.event.clearListeners(myMarker, 'dragend');
google.maps.event.clearListeners(myMarker, 'dragstart');
drag(myMarker, geocoder, map);
});
drag(myMarker, geocoder, map);
map.setCenter(myMarker.position);
myMarker.setMap(map);
}
function drag(myMarker, geocoder, map) {
geocodeLatLng(geocoder, map, myMarker.getPosition().lat(), myMarker.getPosition().lng());
google.maps.event.addListener(myMarker, 'dragend', function (evt) {
document.getElementById('current').innerHTML = '<p>Lat: ' + evt.latLng.lat().toFixed(3) + ' Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
geocodeLatLng(geocoder, map, evt.latLng.lat(), evt.latLng.lng());
});
google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
document.getElementById('current').innerHTML = '<p>Waiting...</p>';
});
}
function geocodeLatLng(geocoder, map, lat, lng) {
var input = lat + "," + lng;
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[0]) {
console.log(results[0])
var data_arr = []
document.getElementById("data_area").innerHTML = "";
var data_country = results[0].address_components.find(function(element) {
return element.types[0] == "country";
});
var data_administrative_1 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_1";
});
var data_administrative_2 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_2";
});
var data_administrative_3 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_3";
});
var data_administrative_4 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_4";
});
var data_route = results[0].address_components.find(function(element) {
return element.types[0] == "route";
});
if (data_route !== undefined) {data_arr.push(data_route["long_name"]);}
if (data_administrative_4 !== undefined) {data_arr.push(data_administrative_4["long_name"]);}
if (data_administrative_3 !== undefined) {data_arr.push(data_administrative_3["long_name"]);}
if (data_administrative_2 !== undefined) {data_arr.push(data_administrative_2["long_name"]);}
if (data_administrative_1 !== undefined) {data_arr.push(data_administrative_1["long_name"]);}
if (data_country !== undefined) {data_arr.push(data_country["long_name"]);}
data_arr.forEach(function(data) {
var node = document.createElement("LI");
var textnode = document.createTextNode(data);
node.appendChild(textnode);
document.getElementById("data_area").appendChild(node);
});
} else {
window.alert('No data!');
}
} else {
window.alert('Geocoder failed: ' + status);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=places&key=MY_API_KEY&callback=initMap"></script>
</body>
</html>
The Autocomplete service returns the geometry of the location selected, zoom the map to show those bounds (in the fiddle/snippet I added a rectangle to show the bounds returned, if you don't want that displayed, remove it):
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else if (place.geometry.bounds) {
map.fitBounds(place.geometry.bounds);
}
proof of concept fiddle
html,
body {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
#map_canvas {
width: 100%;
height: 80%;
}
#current {
padding-top: 5px;
}
<label>Enter address:</label><br>
<input id="searchTextField" type="text" size="50" style="margin-bottom: 20px;">
<section style="width: 100%; height:100%;">
<div id='map_canvas' style=""></div>
<div id="current">No info...</div>
</section>
<div style="margin-top: 10px;" id="data_area"></div>
<script>
var rect;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(41.0082, 28.9784),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(41.0082, 28.9784),
draggable: true
});
var geocoder = new google.maps.Geocoder;
var markers = [];
markers.push(myMarker);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
map.addListener('idle', function() {
console.log(map.getBounds());
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
if (rect && rect.setMap) rect.setMap(null);
rect = new google.maps.Rectangle({
map: map,
bounds: place.geometry.viewport
})
} else if (place.geometry.bounds) {
map.fitBounds(place.geometry.bounds);
if (rect && rect.setMap) rect.setMap(null);
rect = new google.maps.Rectangle({
map: map,
bounds: place.geometry.bounds
})
}
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng()),
draggable: true
});
markers.push(myMarker);
map.setCenter(myMarker.position);
myMarker.setMap(map);
google.maps.event.clearListeners(myMarker, 'dragend');
google.maps.event.clearListeners(myMarker, 'dragstart');
drag(myMarker, geocoder, map);
});
drag(myMarker, geocoder, map);
map.setCenter(myMarker.position);
myMarker.setMap(map);
}
function drag(myMarker, geocoder, map) {
geocodeLatLng(geocoder, map, myMarker.getPosition().lat(), myMarker.getPosition().lng());
google.maps.event.addListener(myMarker, 'dragend', function(evt) {
document.getElementById('current').innerHTML = '<p>Lat: ' + evt.latLng.lat().toFixed(3) + ' Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
geocodeLatLng(geocoder, map, evt.latLng.lat(), evt.latLng.lng());
});
google.maps.event.addListener(myMarker, 'dragstart', function(evt) {
document.getElementById('current').innerHTML = '<p>Waiting...</p>';
});
}
function geocodeLatLng(geocoder, map, lat, lng) {
var input = lat + "," + lng;
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[0]) {
console.log(results[0])
var data_arr = []
document.getElementById("data_area").innerHTML = "";
var data_country = results[0].address_components.find(function(element) {
return element.types[0] == "country";
});
var data_administrative_1 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_1";
});
var data_administrative_2 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_2";
});
var data_administrative_3 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_3";
});
var data_administrative_4 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_4";
});
var data_route = results[0].address_components.find(function(element) {
return element.types[0] == "route";
});
if (data_route !== undefined) {
data_arr.push(data_route["long_name"]);
}
if (data_administrative_4 !== undefined) {
data_arr.push(data_administrative_4["long_name"]);
}
if (data_administrative_3 !== undefined) {
data_arr.push(data_administrative_3["long_name"]);
}
if (data_administrative_2 !== undefined) {
data_arr.push(data_administrative_2["long_name"]);
}
if (data_administrative_1 !== undefined) {
data_arr.push(data_administrative_1["long_name"]);
}
if (data_country !== undefined) {
data_arr.push(data_country["long_name"]);
}
data_arr.forEach(function(data) {
var node = document.createElement("LI");
var textnode = document.createTextNode(data);
node.appendChild(textnode);
document.getElementById("data_area").appendChild(node);
});
} else {
window.alert('No data!');
}
} else {
window.alert('Geocoder failed: ' + status);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
Related
I have error with google map when it put Marker it get this error
I do not know what the error is when I click on save it outputs that the data is field is required. in the map it selects the place but when I click on the place this error comes out at the bottom
VM951 livewire.js:13 Uncaught TypeError: Cannot read properties of undefined (reading '$wire')
at Livewire.value (VM951 livewire.js:13:145634)
at placeMarkerAndPanTo (make:2811:27)
at make:2792:11
at geocoder.js:6:1385
at geocoder.js:3:420
at bza (geocoder.js:2:218)
at gia.e [as m] (geocoder.js:3:339)
at Object.c [as _yj5gms] (common.js:123:253)
at GeocodeService.Search?5m2&1d24.745676471010597&2d46.7278229712639&9sen-US&callback=_xdc_._yj5gms&key=AIzaSyDy4tKkS30XU9DJsUA5cqLzg-jtynKS18s&token=45746:1:28
I do not know what the error is when I click on save it outputs that the data is field is required. in the map it selects the place but when I click on the place this error comes out at
this is my code
#section('scripts')
<script src="https://maps.googleapis.com/maps/api/js?key={{env("GOOGLE_KEY")}}&libraries=places&v=weekly"> </script>
<script src="{{ asset('dashboard/assets/js/pages/crud/forms/widgets/select2.js') }}"></script>
<script>
$(document).ready(function() {
$('#kt_select2_3').select2({
placeholder: '',
}).on('change', function() {
#this.properties = $(this).val();
});
});
function mapLocation() {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var lat, lng;
var markers = [];
var gmarkers = [];
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var riyad = new google.maps.LatLng(24.729518, 46.723341);
var mapOptions = {
zoom: 13,
center: riyad,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
map.addListener('click', function(e) {
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': e.latLng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//alert(results[1].formatted_address);
if (results[1]) {
//results = results[1];
//var result12 = results[1].formatted_address;
// //document.getElementById("address_pickUp").innerHTML = results[1].formatted_address;
// // alert(document.getElementById("address_pickUp").innerHTML.length)
// if(document.getElementById("address_pickUp").innerHTML.length == 0){
// document.getElementById("address_pickUp").innerHTML = results[1].formatted_address;
// }else{
// document.getElementById("address_dropOff").innerHTML = results[1].formatted_address;
// }
//#this.address = results[1].formatted_address;
// alert("Location: " + results[1].formatted_address + "\r\nLatitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
//alert(result12);
}
}
placeMarkerAndPanTo(e.latLng, map, results[1].formatted_address);
});
});
var marker = new google.maps.Marker({
// position: markers[0],
position: markers,
map: map
});
function placeMarkerAndPanTo(latLng, map, results) {
if (document.getElementById("pickup_lat").value.length == 0) {
document.getElementById("pickup_lat").value = latLng.lat();
document.getElementById("pickup_lng").value = latLng.lng();
document.getElementById("address_pickUp").value = results;
marker.setPosition(latLng);
map.panTo(latLng);
#this.pickup_lat = latLng.lat();
#this.pickup_lng = latLng.lng();
} else {
document.getElementById("dropoff_lat").value = latLng.lat();
document.getElementById("dropoff_lng").value = latLng.lng();
document.getElementById("address_dropOff").value = results;
marker.setPosition(latLng);
map.panTo(latLng);
#this.dropoff_lat = latLng.lat();
#this.dropoff_lng = latLng.lng();
}
}
directionsDisplay.setMap(map);
google.maps.event.addDomListener(document.getElementById('routebtn'), 'click', calcRoute);
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
console.log("latitude: " + place.geometry.location.lat() + ", longitude: " + place.geometry.location.lng());
/*if (document.getElementById("pickup_lat").value.length == 0) {
document.getElementById("pickup_lat").value = place.geometry.location.lat();
document.getElementById("pickup_lng").value = place.geometry.location.lng();
// marker.setPosition(latLng);
// map.panTo(latLng);
//#this.pickup_lat = place.geometry.location.lat();
//#this.pickup_lng = place.geometry.location.lng();
} else {
document.getElementById("dropoff_lat").value = place.geometry.location.lat();
document.getElementById("dropoff_lng").value = place.geometry.location.lng();
}*/
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
#endsection
make-trip.blade.php
<div class="col-lg-12" wire:ignore>
<div class="col-lg-3">
<x-input type="text" field="map" style="margin: 10px; z-index: 0; position: absolute; cursor: pointer; left: 0px; top: 0px;width:350px" placeholder="Search Box" id="pac-input"></x-input>
</div>
I do no now what is the error
I have this project with Google Maps API. Everything works perfectly except that Google Marker added through an input value is not showing. I have inputs, of which two are origin and destination respectively, with direction both show perfectly but the third input which is added later doesn't show. I have a different function to take care of it though.
<input type="text" class="form-control" id="origin_input" name="origin_input">
<input type="text" class="form-control" id="destination_input" name="destination_input">
<input type="text" class="form-control" id="stopOver">
And here is my JavaScript for the Google Map:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {
lat: 7.946527,
lng: -1.023194
},
zoom: 8
});
new AutocompleteDirectionsHandler(map);
addStopOverMarker(map);
}
function addStopOverMarker(map) {
this.map = map;
var stopOver = new google.maps.places.Autocomplete(document.getElementById('stopOver'));
google.maps.event.addListener(stopOver, 'place_changed', function() {
var coord = stopOver.getPlace().geometry.location;
console.log(coord);
window.post = coord;
});
var marker = new google.maps.Marker({
position: window.post,
icon: 'https://png.icons8.com/color/50/000000/street-view.png',
map: map,
draggable: true,
visible: true
});
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
var originInput = document.getElementById('origin_input');
var destinationInput = document.getElementById('destination_input');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
// this.service = new google.maps.DistanceMatrixService;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {
placeIdOnly: true
});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {
placeIdOnly: true
});
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {
'placeId': this.originPlaceId
},
destination: {
'placeId': this.destinationPlaceId
},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
You have three issues with your addStopover function:
you are using the wrong map variable
the icon doesn't exists
you are creating the marker before the place_changed event fires and it's callback function runs
working version of the function:
function addStopOverMarker(map) {
var stopOver = new google.maps.places.Autocomplete(document.getElementById('stopOver'));
google.maps.event.addListener(stopOver, 'place_changed', function() {
var coord = stopOver.getPlace().geometry.location;
console.log(coord);
var marker = new google.maps.Marker({
position: coord,
map: map,
draggable: true,
visible: true
});
});
}
proof of concept fiddle
code snippet:
html,
body,
#map {
height: 90%;
width: 100%;
margin: 0px;
padding: 0px;
}
<div id="map"></div>
<input id="origin_input" value="Tecmiman" />
<input id="destination_input" value="Kumasi" />
<input id="stopOver" value="Bechem" />
<script>
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {
lat: 7.946527,
lng: -1.023194
},
zoom: 8
});
new AutocompleteDirectionsHandler(map);
addStopOverMarker(map);
}
function addStopOverMarker(map) {
var stopOver = new google.maps.places.Autocomplete(document.getElementById('stopOver'));
google.maps.event.addListener(stopOver, 'place_changed', function() {
var coord = stopOver.getPlace().geometry.location;
console.log(coord);
var marker = new google.maps.Marker({
position: coord,
map: map,
draggable: true,
visible: true
});
});
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
var originInput = document.getElementById('origin_input');
var destinationInput = document.getElementById('destination_input');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
// this.service = new google.maps.DistanceMatrixService;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {
placeIdOnly: true
});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {
placeIdOnly: true
});
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {
'placeId': this.originPlaceId
},
destination: {
'placeId': this.destinationPlaceId
},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap"></script>
Im trying to change geocoded informations from Schwartmecke 49, 57399 Kirchhundem, Germany to just Schwartmecke 49, Germany , but dont know how. Can anybode help me ? Thanks
<script type="text/javascript">
var map;
var geocoder;
var centerChangedLast;
var reverseGeocodedLast;
var currentReverseGeocodeResponse;
function initialize() {
var latlng = new google.maps.LatLng(49.624935522974546, 15.46877500000007);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
setupEvents();
centerChanged();
}
function setupEvents() {
reverseGeocodedLast = new Date();
centerChangedLast = new Date();
setInterval(function() {
if((new Date()).getSeconds() - centerChangedLast.getSeconds() > 1) {
if(reverseGeocodedLast.getTime() < centerChangedLast.getTime())
reverseGeocode();
}
}, 1000);
google.maps.event.addListener(map, 'zoom_changed', function() {
document.getElementById("zoom_level").innerHTML = map.getZoom();
});
google.maps.event.addListener(map, 'center_changed', centerChanged);
google.maps.event.addDomListener(document.getElementById('crosshair'),'dblclick', function() {
map.setZoom(map.getZoom() + 1);
});
}
function getCenterLatText() {
return '(' + map.getCenter().lat() +')';
}
function getCenterLngText() {
return '(' + map.getCenter().lng() +')';
}
function centerChanged() {
centerChangedLast = new Date();
var lat = getCenterLatText();
var lng = getCenterLngText();
document.getElementById('lat').innerHTML = lat;
document.getElementById('lng').innerHTML = lng;
document.getElementById('formatedAddress').value = '';
currentReverseGeocodeResponse = null;
}
function reverseGeocode() {
reverseGeocodedLast = new Date();
geocoder.geocode({latLng:map.getCenter()},reverseGeocodeResult);
}
function reverseGeocodeResult(results, status) {
currentReverseGeocodeResponse = results;
if(status == 'OK') {
if(results.length == 0) {
document.getElementById('formatedAddress').value = 'None';
} else {
document.getElementById('formatedAddress').value = results[0].formatted_address;
}
} else {
document.getElementById('formatedAddress').value = 'Error';
}
}
function geocode() {
var address = document.getElementById("address").value;
geocoder.geocode({
'address': address,
'partialmatch': true}, geocodeResult);
}
function geocodeResult(results, status) {
if (status == 'OK' && results.length > 0) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
}
function addMarkerAtCenter() {
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
if(currentReverseGeocodeResponse) {
var addr = '';
if(currentReverseGeocodeResponse.size == 0) {
addr = 'None';
} else {
addr = currentReverseGeocodeResponse[0].formatted_address;
}
text = '<br>' + 'address: <br>' + addr;
}
var infowindow = new google.maps.InfoWindow({ content: text });
}
</script>
Hope i explained my problem enough.
In your reverseGeocodeResult() function, you take the first result and return its "formatted address" property.
Instead of returning this, try browsing its "address_components" property.
See more at
https://developers.google.com/maps/documentation/geocoding/#JSON
IE7 is giving me an issue with a script, using Google Maps API.
When the page is loaded, it says in a alert box 'undefined not found'.
This only happens in IE7, not IE8, nor IE9. Fine in other browsers too, i guess there is a coding error. As soon as i take out JS, no warning but map doesn't work, obviously.
Here is my entire JS. Thanks in advance!
var map;
var markers = [];
var infoWindow;
var panorama;
function init_map() {
map = new google.maps.Map(document.getElementById("map"), {
//center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap',
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
});
infoWindow = new google.maps.InfoWindow();
var address = $('#address').val();
var address_optional = $('#address_optional').val();
if (address == '' && address_optional != '1') init_location();
else searchLocations(address_optional);
}
function init_location(lat, lng, zoom) {
if (lat === undefined) lat = 40;
if (lng === undefined) lng = -100;
if (zoom === undefined) zoom = 4;
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(lat, lng),
zoom: zoom,
mapTypeId: 'roadmap',
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
});
}
$("#next").live('click', function(event) {
event.preventDefault();
var page_number = $('body').data("page_number");
$('body').data("page_number", (page_number + 1));
searchLocations();
});
$("#previous").live('click', function(event) {
event.preventDefault();
var page_number = $('body').data("page_number");
$('body').data("page_number", (page_number - 1));
searchLocations();
});
function searchLocations() {
var address = $('#address').val();
var geocoder = new google.maps.Geocoder();
var address_optional = $('#address_optional').val();
geocoder.geocode({
address: address
}, function(results, status) {
if ((status == google.maps.GeocoderStatus.OK)) {
searchLocationsNear(results[0].geometry.location);
} else {
if (address_optional == '1') {
searchLocationsNear('', 1);
} else {
alert(address + ' not found');
}
}
});
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
}
function createSidebarEntry(markerNum, sidebarContent, markerContent, lat, lng) {
var div = document.createElement('div');
div.innerHTML = sidebarContent;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
div.onclick = function() {
infoWindow.setContent(markerContent);
infoWindow.open(map, markers[markerNum]);
init_location(lat, lng, 16);
var latlng = new google.maps.LatLng(
parseFloat(lat), parseFloat(lng));
createMarker(latlng, lat, lng, markerContent);
}
return div;
}
function resizeMap(width, height) {
$('#map').animate({
width: width,
height: height
}, function() {
google.maps.event.trigger(map, 'resize');
map.setCenter(map.getCenter());
});
}
function streetView(lat, lng) {
var dom = 'streetview';
panorama = new google.maps.StreetViewPanorama(document.getElementById(dom));
displayStreetView(lat, lng, dom);
if ($('#map').height() == 600) {
resizeMap(850, 300);
$('#streetview').height(300);
}
}
function searchLocationsNear(center, address_optional) {
clearLocations();
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = '';
var page_number = $('body').data("page_number");
if (page_number == null) {
page_number = 1;
$('body').data("page_number", page_number);
}
var categoryid = $('#categoryid').val();
if (address_optional == '1') var searchUrl = 'map_data.php?categoryid=' + categoryid + '&page_number=' + page_number + '&address_optional=' + address_optional;
else var searchUrl = 'map_data.php?lat=' + center.lat() + '&lng=' + center.lng() + '&categoryid=' + categoryid + '&page_number=' + page_number;
//alert(searchUrl);
$.ajax({
type: 'GET',
url: searchUrl,
dataType: 'json',
success: function(msg) {
var locations = msg.locations;
var markersContent = msg.markersContent;
var sidebarContent = msg.sidebarContent;
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var name = locations[i]['name'];
var address = locations[i]['address'];
var distance = parseFloat(locations[i]['distance']);
var latlng = new google.maps.LatLng(
parseFloat(locations[i]['lat']), parseFloat(locations[i]['lng']));
var sidebarEntry = createSidebarEntry(i, sidebarContent[i], markersContent[i], locations[i]['lat'], locations[i]['lng']);
sidebar.appendChild(sidebarEntry);
createOption(name, distance, i);
createMarker(latlng, locations[i]['lat'], locations[i]['lng'], markersContent[i]);
bounds.extend(latlng);
}
$('#pagination').html(msg.pagination);
map.fitBounds(bounds);
}
});
resizeMap(850, 600);
$('#streetview').html('').height(0);
}
function createMarker(latlng, lat, lng, html) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, this);
});
$("#sidebar div").click(function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
}
function displayStreetView(lat, lng, dom) {
var latlng = new google.maps.LatLng(lat, lng);
var panoramaOptions = {
position: latlng,
pov: {
heading: 270,
pitch: 0,
zoom: 1
}
};
panorama = new google.maps.StreetViewPanorama(document.getElementById(dom), panoramaOptions);
map.setStreetView(panorama);
}
I want to set a marker when I open up my google maps page on my current location.
This marker needs to be changed when I enter an adress in the textfield.
I have no clue how I have to add the standard marker on my location and update it when an adress is entered in the textfield.
I already have the Lat & long of the current position.
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"
type="text/javascript"></script>
<style type="text/css">
body {
font-family: sans-serif;
font-size: 14px;
}
#map_canvas {
height: 400px;
width: 600px;
margin-top: 0.6em;
}
</style>
<script type="text/javascript">
var gl;
var ownlat;
var ownlng;
function displayPosition(position)
{
ownlat = position.coords.latitude;
ownlng = position.coords.longitude;
var p = document.getElementById("p");
p.innerHTML = "Own Latitude = " + ownlat + " <br/>" +
"Own Longitude = " + ownlng;
}
function displayError(positionError)
{
alert("error " + positionError.code);
}
try
{
if (typeof navigator.geolocation === 'undefined')
{
gl = google.gears.factory.create('beta.geolocation');
} else {
gl = navigator.geolocation;
}
} catch(e) {}
if (gl)
{
gl.getCurrentPosition(displayPosition, displayError);
} else
{
alert("Geolocation services are not supported by your web browser.");
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
var image = new google.maps.MarkerImage(
place.icon,
new google.maps.Size(71, 71),
new google.maps.Point(0, 0),
new google.maps.Point(17, 34),
new google.maps.Size(35, 35));
marker.setIcon(image);
marker.setPosition(place.geometry.location);
var address = '';
if (place.address_components) {
address = [(place.address_components[0] &&
place.address_components[0].short_name || ''),
(place.address_components[1] &&
place.address_components[1].short_name || ''),
(place.address_components[2] &&
place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
//GET LAT & LONG
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
document.getElementById('lat').innerHTML = lat;
document.getElementById('long').innerHTML = long;
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>