jansepke
jansepke

Reputation: 1979

Put marker into country from country name

I have a google maps search field. The input goes to the google places API and I get a result and do a zoom to the boundaries of that place.

If the user searches for a country like Norway the map will zoom and center like this: https://www.google.de/maps/place/Norwegen/@64.5783089,17.888237,5z/data=!3m1!4b1!4m2!3m1!1s0x461268458f4de5bf:0xa1b03b9db864d02b

but I have the requirement to place a marker into the center so the user sees where his search took him. In the Norway example this would result in a marker being placed in the middle of the screen, but outside of Norway.

Is there any possibility to place a marker into a country?

EDIT

The place json if I search for Norway:

{
    "address_components": [
        {
            "long_name": "Norway",
            "short_name": "NO",
            "types": [
                "country",
                "political"
            ]
        }
    ],
    "adr_address": "<span class=\"country-name\">Norway</span>",
    "formatted_address": "Norway",
    "geometry": {
        "location": {
            "k": 60.47202399999999,
            "D": 8.46894599999996
        },
        "viewport": {
            "Ea": {
                "k": 57.9711417,
                "j": 71.1854762
            },
            "wa": {
                "j": 4.626684800000021,
                "k": 31.149789199999987
            }
        }
    },
    "icon": "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
    "id": "c94d4f99cf5b1f973f837eb189e0cfff6b91fab0",
    "name": "Norway",
    "place_id": "ChIJv-VNj0VoEkYRK9BkuJ07sKE",
    "reference": "CnRpAAAANAQEnqw1T_JMzZwRKpmAX1Yz7vZ83m1zIb20hhZVPnSrTHQN1nELF5mq73UIhsU5HpsvQV3KZWyIaEBu-WoCI0R10koCHxf3zV6FsWeS0d_GsY-rK9a6i4z0MKBSZVNTywLbZBKDIuoiZEIldqmMjxIQ94Ks-CUSOr9ciS0K8TLnmRoUTp5kU7pNMCjEfDZGde6GvYtDLGU",
    "scope": "GOOGLE",
    "types": [
        "country",
        "political"
    ],
    "url": "https://maps.google.com/maps/place?q=Norway&ftid=0x461268458f4de5bf:0xa1b03b9db864d02b",
    "html_attributions": []
} 

google recognizes it as a country and the viewport is used for the bounds, but geometry.location is in Sweden.

Upvotes: 2

Views: 664

Answers (2)

Dr.Molle
Dr.Molle

Reputation: 117334

the geometry of a places-result contains 2 properties, the viewport(I guess that's what you use to zoom to the bounds) and also a location-property. This location-property usually will be a point inside the country(when you search for a country), you may use it to draw the marker.

Upvotes: 1

MrUpsidown
MrUpsidown

Reputation: 22486

Look at the PlaceGeometry object.

This will allow you to place a marker correctly. For example:

var marker = new google.maps.Marker({
    map: map,
    title: place.name,
    position: place.geometry.location
});

Here is an example fiddle I created some time ago:

JSFiddle demo

Upvotes: 1

Related Questions